文件中没有保存任何内容
这是将用户输入的数据保存到文件中的代码片段。这工作正常。即它在所需位置创建文件,但问题是创建的文件是空的。这是什么原因呢?
JFileChooser save = new JFileChooser();
int option = save.showSaveDialog( this );
if( option == JFileChooser.APPROVE_OPTION ) {
try {
BufferedWriter writer = new BufferedWriter( new FileWriter( save.getSelectedFile().getPath() + ".txt") );
String messageToBeSaved = jTextArea2.getText();
int lengthOfMessage = messageToBeSaved.length();
writer.write( messageToBeSaved, 0 , lengthOfMessage );
JOptionPane.showMessageDialog(new JFrame() , "Message saved");
} catch(Exception exc) {
System.out.println(exc);
}
如果这个片段有任何问题,请告诉我哪里出错了。
This is the snippet that saves the data entered by the user into the file. This works fine.i.e it creates the file at the wanted location but the problem is that the file created is empty. What is the reason for this ?
JFileChooser save = new JFileChooser();
int option = save.showSaveDialog( this );
if( option == JFileChooser.APPROVE_OPTION ) {
try {
BufferedWriter writer = new BufferedWriter( new FileWriter( save.getSelectedFile().getPath() + ".txt") );
String messageToBeSaved = jTextArea2.getText();
int lengthOfMessage = messageToBeSaved.length();
writer.write( messageToBeSaved, 0 , lengthOfMessage );
JOptionPane.showMessageDialog(new JFrame() , "Message saved");
} catch(Exception exc) {
System.out.println(exc);
}
If there is anything wrong with this snippet,please tell where i am going wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
由于它是一个缓冲写入器,因此您应该刷新并关闭它。
尝试添加以下内容:
为了完全正确,您应该在
finally
块中关闭编写器。编辑:刷新并不是真正需要的,因为关闭无论如何都会刷新。
Since it is a buffered writer, you should flush and close it.
Try adding this:
To be completely correct, you should close your writer in a
finally
block.Edit: The flush is not really required since close will flush anyways.
向 BufferedWriter 写入数据后,应将其关闭。这将刷新缓冲区,然后关闭它。
You should close the
BufferedWriter
after you have written data to it. That will flush the buffer, and then close it.您必须
关闭
写入器,然后缓冲区的内容将被刷新到磁盘。You have to
close
thewriter
, then the contents of the buffer will be flushed to the disk.可能是因为您没有 flushing< /a> 流。
Probably because you are not flushing the stream.
完成后您应该调用 write.close() 。
You should call write.close() when you are done.