零基礎寫Java知乎爬蟲之將抓取的內容儲存到本地_java

來源:互聯網
上載者:User

說到Java的本機存放區,肯定使用IO流進行操作。
首先,我們需要一個建立檔案的函數createNewFile:

複製代碼 代碼如下:

public static boolean createNewFile(String filePath) { 
        boolean isSuccess = true; 
        // 如有則將"\\"轉為"/",沒有則不產生任何變化 
        String filePathTurn = filePath.replaceAll("\\\\", "/"); 
        // 先過濾掉檔案名稱 
        int index = filePathTurn.lastIndexOf("/"); 
        String dir = filePathTurn.substring(0, index); 
        // 再建立檔案夾 
        File fileDir = new File(dir); 
        isSuccess = fileDir.mkdirs(); 
        // 建立檔案 
        File file = new File(filePathTurn); 
        try { 
            isSuccess = file.createNewFile(); 
        } catch (IOException e) { 
            isSuccess = false; 
            e.printStackTrace(); 
        } 
        return isSuccess; 
    } 

然後,我們需要一個寫入檔案的函數:


public static boolean writeIntoFile(String content, String filePath, 
            boolean isAppend) { 
        boolean isSuccess = true; 
        // 先過濾掉檔案名稱 
        int index = filePath.lastIndexOf("/"); 
        String dir = filePath.substring(0, index); 
        // 建立除檔案的路徑 
        File fileDir = new File(dir); 
        fileDir.mkdirs(); 
        // 再建立路徑下的檔案 
        File file = null; 
        try { 
            file = new File(filePath); 
            file.createNewFile(); 
        } catch (IOException e) { 
            isSuccess = false; 
            e.printStackTrace(); 
        } 
        // 寫入檔案 
        FileWriter fileWriter = null; 
        try { 
            fileWriter = new FileWriter(file, isAppend); 
            fileWriter.write(content); 
            fileWriter.flush(); 
        } catch (IOException e) { 
            isSuccess = false; 
            e.printStackTrace(); 
        } finally { 
            try { 
                if (fileWriter != null) 
                    fileWriter.close(); 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
        } 
 
        return isSuccess; 
    } 

我們把這兩個函數封裝到一個FileReaderWriter.java檔案中以便後續使用。
接著我們回到知乎爬蟲中。
我們需要給知乎的Zhihu封裝類加個函數,用來格式化寫入到本地時的排版。

OK,這樣就差不多了,接下來吧mian方法中的System.out.println改成

運行,便可以看到本來在控制台看到的內容已經被寫到了本地的txt檔案裡:

大體一看沒什麼問題,仔細看看發現問題:存在太多的html標籤,主要是<b>和<br>。
我們可以在輸出的時候對這些標記進行處理。
先把<br>換成io流裡面的\r\n,再把所有的html標籤都刪除,這樣看起來便會清晰很多。

這裡的replaceAll函數可以使用正則,於是所有的<>標籤在最後就都被刪除了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.