FileReader类读取文本文件默认是按照utf-8编码读取,若文本文件不是utf-8编码则会出现中文乱码情况。转换流可以解决中文乱码问题。
案例:将字节流FileInputStream包装成字符流InputStreamReader,对文件按照gbk编码进行读取,进而再包装成BufferedReader。代码如下:
@Test public void readFile() { BufferedReader br = null; String line; try { br = new BufferedReader(new InputStreamReader(new FileInputStream("e:\\test.txt"), "gbk")); while ((line = br.readLine()) != null) { System.out.println(line); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } }
案例:将字节流FileOutputStream包装成字符流OutputStreamWriter,对文件按照gbk编码进行写入,进而再包装成BufferedWriter。代码如下:
@Test public void writeFile() { BufferedWriter bw = null; try { bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("e:\\test.txt"))); bw.write("hello world"); bw.newLine(); bw.write("hello java"); bw.newLine(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (bw != null) { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } }