解決 java BufferedReader.readLine()方法按行讀取文件內容中文亂碼的問題

原來的代碼如下所示,但是輸出的內容都是亂碼

public void readLine(String path) {
    InputStreamReader isr = null;
    BufferedReader br = null;
    try {
        isr = new InputStreamReader(new FileInputStream(path));
        br = new BufferedReader(isr);
        String str;
        // 通過readLine()方法按行讀取字符串
        while ((str = br.readLine()) != null) {
            System.out.println(str);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 統一在finally中關閉流,防止發生異常的情況下,文件流未能正常關閉
        try {
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

解決辦法是在創建InputStreamReader對象的時候制定文件的編碼

我先用EditPlus打開文件,在右下角可以看到文件的編碼爲ANSI,但是在代碼中設置編碼爲ANS後卻報Unknown encoding:'ANSI'錯誤

憑藉以往的經驗,Window中中文編碼一般爲GBK,設置後果然不報紅,而且運行後也能夠成功輸出中文了

以下爲修改後正常運行的代碼

public void readLine(String path) {
    InputStreamReader isr = null;
    BufferedReader br = null;
    try {
        isr = new InputStreamReader(new FileInputStream(path), "GBK");
        br = new BufferedReader(isr);
        String str;
        // 通過readLine()方法按行讀取字符串
        while ((str = br.readLine()) != null) {
            System.out.println(str);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 統一在finally中關閉流,防止發生異常的情況下,文件流未能正常關閉
        try {
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

 

 

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