Java下载网页
如何读取和下载一个网页?
解决方法
下面的示例显示了如何使用net.URL类的URL()建构函数阅读和下载网页。
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.InputStreamReader; import java.net.URL; public class Main { public static void main(String[] args) throws Exception { URL url = new URL("http://www.gitbook.net"); BufferedReader reader = new BufferedReader (new InputStreamReader(url.openStream())); BufferedWriter writer = new BufferedWriter (new FileWriter("data.htmll")); String line; while ((line = reader.readLine()) != null) { System.out.println(line); writer.write(line); writer.newLine(); } reader.close(); writer.close(); } }
结果
上面的代码示例将产生以下结果。
Welcome to Java Tutorial Here we have plenty of examples for you! Come and Explore Java!