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!