java jfilechooser 保存,如何在Java中使用JFileChooser保存文件?

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值