无法写任何文件

Com*_*erd 0 java debugging file-io

我正在尝试写入文件

try
{
    PrintWriter fileout = new PrintWriter("./src/javaapplication1/test.dat");

    for(int i=0;i<10;i++)
    {
         fileout.println(i);
    }
 }
 catch (IOException e)
 {
      System.out.println("File cannot be created");

 }
Run Code Online (Sandbox Code Playgroud)

但是,我期待没有任何内容写入文件

1
2
3
4
5
6
7
8
9
Run Code Online (Sandbox Code Playgroud)

我写这个文件的方式有什么问题?

Jon*_*eet 5

你没有关闭作家.它几乎肯定只是缓冲了所有数据.

您应该始终关闭IO流等.如果您使用的是Java 7+,则可以使用try-with-resources语句:

try (PrintWriter fileout = new PrintWriter("./src/javaapplication1/test.dat")) {
    for (int i = 0; i < 10; i++) {
        fileout.println(i);
    }
} catch (IOException e) {
    // Don't just swallow the exception - use that information!
    System.out.println("Error writing file: " + e);
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是早期版本的Java,则应使用finally块来关闭编写器是否抛出异常.