java8 实现网页下载,大致分为4步,分别是:给定目标网页链接->与目标主机建立连接->读入网页文件流->写入本地文件 。会用到
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 = "http://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;
}
}
文中如未加特殊声明均为原创,转载请注明:转自于杨圣亮的技术博客 链接地址:Java8 实现下载网页的完整代码