Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save file using JFileChooser in Java? [closed]

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();
        }
    }
}
like image 764
Michał Tabor Avatar asked Jan 29 '13 18:01

Michał Tabor


3 Answers

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.

like image 63
Ryan Amos Avatar answered Oct 23 '22 22:10

Ryan Amos


Don't forget to flush and close your FileWriter.

like image 30
Dan D. Avatar answered Oct 23 '22 23:10

Dan D.


You need to close() your FileWriter.

like image 5
SLaks Avatar answered Oct 23 '22 22:10

SLaks