输入输出流的一些细节问题

1、写文本文件


  第一个参数:写入文件需要指定文件名,如果不指定的文件不存在,会自动创建文件;如果存在,会自动覆盖以前的内容。

  第二个参数:指定文件是否以追加的方式写入文件。

io.FileWriter.FileWriter(String fileName, boolean append)
FileWriter fw = null;
try {
    fw = new FileWriter("E:/hello.txt", true);
  char[] c = {'a', 'b', 'c', 'd'}; fw.write(
c); } catch (IOException e) { e.printStackTrace(); } finally { if (fw != null) { try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } }

结果:
 abcd

1、解决write(char[] c)写入到文件末尾时重复写入的问题


  可以使用如下方法解决这个问题。读取了多少字节就写入多少个字节。

write(char[] c, int start, int end);

代码示例:

char[] cs = new char[1024]; // 创建缓存数组
  int length = -1; 
  while ((length = fr.read(cs)) != -1) {
  fw.write(cs, 0, length);
}
原文地址:https://www.cnblogs.com/snow1234/p/7199810.html