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

3

22

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();
        }
    }
}
Meisel answered 29/1, 2013 at 18:9 Comment(0)
G
24

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.

Gonroff answered 29/1, 2013 at 18:22 Comment(0)
B
6

Don't forget to flush and close your FileWriter.

Barneybarnhart answered 29/1, 2013 at 18:11 Comment(2)
CLOSING helped, now it works. But what means to FLUSH it?Preceptory
See the javadocs: docs.oracle.com/javase/7/docs/api/java/io/Flushable.htmlBarneybarnhart
G
5

You need to close() your FileWriter.

Gillespie answered 29/1, 2013 at 18:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.