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

跟風遠走 提交于 2019-11-29 11:51:59

问题


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();
        }
    }
}

回答1:


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.




回答2:


You need to close() your FileWriter.




回答3:


Don't forget to flush and close your FileWriter.



来源:https://stackoverflow.com/questions/14589386/how-to-save-file-using-jfilechooser-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!