java獲取網頁源代碼並寫入本地文件中


 1 import java.io.*;
 2 import java.net.*;
 3 
 4 public class URLDemo {
 5     public static void main(String args[]){
 6         //確定爬取的網頁地址
 7         String strurl="http://fx7.top";
 8         //建立url爬取核心對象
 9         try {
10             URL url=new URL(strurl);
11             //通過url建立與網頁的連接
12             URLConnection conn=url.openConnection();
13             //通過鏈接取得網頁返回的數據
14             InputStream is=conn.getInputStream();
15             
16             System.out.println(conn.getContentEncoding());
17             //一般按行讀取網頁數據,並進行內容分析
18             //因此用BufferedReader和InputStreamReader把字節流轉化為字符流的緩沖流
19             //進行轉換時,需要處理編碼格式問題
20             BufferedReader br=new BufferedReader(new InputStreamReader(is,"UTF-8"));        
21             //按行讀取並打印
22             File file = new File("E:/FileTest/test.txt");
23             //創建本地文件操作對象
24             if(file.exists()) {
25             //文件不存在
26             System.out.println("目標文件不存在!");
27             try {
28                 //如果目標文件不存在則自動創建
29                 file.createNewFile();
30                 System.out.println("已自動創建文件!");
31             } catch (IOException e) {
32                 System.out.println("自動創建文件失敗!");
33             }        
34         }
35             String line=null;
36             while((line=br.readLine())!=null){
37                 System.out.println(line);
38                 //創建文件輸出流將讀取到的網頁源代碼寫入文件
39                 FileOutputStream fileOutputStream = new FileOutputStream(file,true);
40                 fileOutputStream.write(line.getBytes());
41                 fileOutputStream.close();
42             }
43             
44             br.close();
45         } catch (Exception e) {
46             // TODO Auto-generated catch block
47             e.printStackTrace();
48         }
49         
50     }
51 }        

7月26 日晚 文件操作回顧記錄


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM