写入文件时的奇怪行为

Twa*_*ood 7 java io file-io bufferedwriter printwriter

我正在尝试一些基本的Java I/O操作,我尝试运行以下代码:

public static void main(String[] args) {
    File file = new File("fileWrite2.txt"); // create a File object
      try {
    FileWriter fr = new FileWriter(file);
    PrintWriter pw = new PrintWriter(file); // create a PrintWriter that will send its output to a Writer
    BufferedWriter br =  new BufferedWriter(fr);
    br.write("sdsadasdsa");br.flush();br.append("fffff");br.flush();
    pw.println("howdy"); // write the data
    pw.println("folks");
    pw.flush();
    pw.close();
    } catch (IOException e) {
       e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行上面的命令时,我在创建的文件中得到以下输出:

howdy
folks
f
Run Code Online (Sandbox Code Playgroud)

谁能解释为什么'f'会在最后一行?

Sud*_*hul 7

f来自的遗留字符串br.append("fffff");这是由写在文件中BufferedWriter.

由于两个BufferedWriterPrintWriter写入同一个文件,以书面的内容PrintWriter改写以书面内容BufferedWriter.

但似乎没有.写入的字节数PrintWriter由1表示完全覆盖写入的数据BufferedWriter,从而得到f.

如果将其更改br.append("fffff");br.append("ffffg");,则可以看到g现在已经结束.或者,更改pw.println("folks");pw.println("folks1");将显示先前写入的数据现在被完全覆盖PrintWriter.

所有这些混淆是因为对同一文件对象有2个不同的编写器,这是导致问题的原因.正如@Boris指出的那样,只有一个文件对象的编写器.

注意:测试的另一个有趣的事情是在第二个br.flush();之后移动第二个pw.flush();.

// br.flush(); // moved from here
pw.println("howdy"); // write the data
pw.println("folks");
pw.flush();
br.flush(); // to here
Run Code Online (Sandbox Code Playgroud)

  • 简而言之,每个文件只使用一个`Writer`. (7认同)

shi*_*ari 3

通过执行此操作,您将在 上写入 15 个字符bufferedwriter`

br.write("sdsadasdsa");
br.flush();
br.append("fffff");`
Run Code Online (Sandbox Code Playgroud)

但是当你在 printWriter 上写入时,它会覆盖你这次写入的文件内容

pw.println("howdy"); // write the data
pw.println("folks");
Run Code Online (Sandbox Code Playgroud)

这是 10 个字符,只有两个新行\n,需要 2 个字节,因为我们使用 println 因为\n在 Windows 中会转换为\r\n. 所以总共 14 个。所以 1 个字符保留在那里,即 f