解决 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();
        }
    }
}

 

 

 

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