抓取網頁保存時候的亂碼解決

直接使用FileWriter無法指定編碼方式,OutputStream可以指定


public class transCode {
// 把JSOUP讀取的網頁轉換成HTML格式的文件保存下來進行分析,寫文件時候需要指定編碼的格式
public static  void main(String args[]) throws IOException{
String seed = "http://channel.jd.com/electronic.html";
String docstr = getWebDocstr(seed);
saveFile(docstr);


}


public static String getWebDocstr(String url) throws IOException{//用JSOUP得到文檔對象模型的字符形式
Document doc = Jsoup.connect(url).get();
String docstr = doc.toString();
return docstr;

}

public  static void saveFile(String str){//把讀取的document對象轉變成爲字符串進行讀取並寫入到HTML文件中,指定寫
//輸出寫的編碼格式爲UFT-8
String filepath = "d:/bbc.html";
File file = new File(filepath);
try { 
        
        if (!file.exists()) { 
         file.createNewFile(); 
        } 
        //OutputStreamWriter 是字符流通向字節流的橋樑:可使用指定的 charset 將要寫入流中的字符編碼成字節
        //它使用的字符集可以由名稱指定或顯式給定,否則將接受平臺默認的字符集。 
//爲了獲得最高效率,可考慮將 OutputStreamWriter 包裝到 BufferedWriter 中,以避免頻繁調用轉換器
        OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file),"UTF-8"); 
        BufferedWriter writer=new BufferedWriter(write);   
        //PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filePathAndName))); 
        //PrintWriter writer = new PrintWriter(new FileWriter(filePathAndName)); 
        writer.write(str); 
        writer.close(); 
       } catch (Exception e) { 
        System.out.println("寫文件內容操作出錯"); 
        e.printStackTrace(); 
       } 

}


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章