I have following code. It saves file but with empty content. What's wrong with it?
public void saveMap() {
String sb = "TEST CONTENT";
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("/home/me/Documents"));
int retrival = chooser.showSaveDialog(null);
if (retrival == JFileChooser.APPROVE_OPTION) {
try {
FileWriter fw = new FileWriter(chooser.getSelectedFile()+".txt");
fw.write(sb.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
If you're using Java 7, use try with resources. This is how you would do it:
try(FileWriter fw = new FileWriter(chooser.getSelectedFile()+".txt")) {
fw.write(sb.toString());
}
Try with resources automatically calls close()
upon failure or success.
If you're not using Java 7, don't forget to call close()
. close()
will automatically call flush()
.
...
fw.close();
...
To understand why you need to flush, you need to understand how a FileWriter works. When you say fw.write("blah")
, it actually puts that string into a buffer in memory. Once you fill the buffer, the FileWriter then writes the string to the hard drive. It has this behavior because writing files is much more efficient in large chunks.
If you want to empty the buffer before the buffer reaches capacity, you'll need to tell the FileWriter this by calling flush()
. Calling flush()
can also be very important when communicating, such as over the internet, because you'll need to flush before the other end can see your message. It won't do them much use if your message is just sitting in memory.
Once you're done with any I/O stream, you should call close()
(with the exception of the standard I/O streams). This means the OS no longer has to maintain this stream. In some cases, there are a limited number of streams that can be opened, such as with files, so it is extremely important that you don't forget to close.
When you call close, it actually does two things: it empties the buffer and then closes the stream. This is to make sure that nothing gets left behind before the stream closes.