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:
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.
See more on this question at Stackoverflow