原来的代码如下所示,但是输出的内容都是乱码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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,设置后果然不报红,而且运行后也能够成功输出中文了


以下为修改后正常运行的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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(); } } } |