Java8 实现下载网页的完整代码
java8 实现网页下载,大致分为4步,分别是:给定目标网页链接->与目标主机建立连接->读入网页文件流->写入本地文件 。会用到java io 和 java net库。程序代码如下,留有注释。
package com.yangshengliang.URLDemo; //如果所用 IDE 不是eclipse,请注销这一行 import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.MalformedURLException; import java.net.URL; public class UrlDemo1 { public static void main(String[] args) { try { new UrlDemo1().downloadPage(); } catch (IOException e) { e.printStackTrace(); } } private String downloadPage() throws IOException { // 目标网页链接 String url = "https://www.yangshengliang.com"; String inputLine = null; try { URL pageUrl = new URL(url); BufferedReader br = new BufferedReader(new InputStreamReader(pageUrl.openStream(), "utf-8")); File file = new File("download/index.html"); //程序文件目录建目录 download,用于存放下载的网页 FileOutputStream out = new FileOutputStream(file); OutputStreamWriter write = new OutputStreamWriter(out, "utf-8"); // 将输入流读入到变量中,再写入到文件 while ((inputLine = br.readLine()) != null) { write.write(inputLine); System.out.println(inputLine); } br.close(); write.close(); System.err.println("下载完毕!"); } catch (MalformedURLException e) e.printStackTrace(); } return url; } }
更多阅读