简体   繁体   English

无法将任何内容写入文件

[英]Unable to write anything to file

I am trying to write to file 我正在尝试写入文件

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");

 }

However nothing gets written to the file , I am expecting 但是我期望没有任何写入文件

1
2
3
4
5
6
7
8
9

What is wrong with the way i am writing to the file ?? 我写入文件的方式有什么问题?

You haven't closed the writer. 您尚未关闭作家。 It's almost certainly just buffered all the data. 几乎可以肯定,它只是缓冲了所有数据。

You should always close IO streams etc. If you're using Java 7+, you can use a try-with-resources statement: 您应该始终关闭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);
}

If you're using an earlier version of Java, you should use a finally block to close the writer whether an exception is thrown or not. 如果使用的是Java的早期版本,则无论是否引发异常,都应使用finally块关闭编写器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM