I have this snippet of code:
try {
f1 = new File(\"sink.txt\");
f1.createNewFile();
fw = new FileWriter(f1);
The short answer is that you are not closing (or flushing) your FileWriter
. That means that you application will exit with unwritten data still sitting in the file buffers.
There are a number of other mistakes in your code. Starting from the top:
try {
f1 = new File("sink.txt");
f1.createNewFile();
fw = new FileWriter(f1);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The createNewFile
call is redundant. The following new FileWriter
will create the file.
You are catching exceptions and continuing as if nothing has happened. You >>cannot<< continue from those exceptions. The rest of your code can only work properly if you succeeded in opening the file.
You don't need to catch FileNotFoundException
unless you intend to handle it differently. Catching IOException
is sufficient, because it is a superclass of the former.
At this point, you should be using try-with-resources:
f1 = new File("sink.txt");
try (FileWriter fw = new FileWriter(f1)) {
// compute stuff
// write stuff to file
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
} catch (IOException ex) {
// This is ugly for a real app. However, an IOException that
// is not a FileNotFoundException is "unexpected" at this point
// and providing a user-friendly explanation would be tricky.
ex.printStackTrace();
}
The try-with-resources will cause fw
to be closed automatically when the block exits. Closing the writer will first flush it.