单击按钮时,我尝试使用JFileChooser
保存文件。
因此,当我单击它时,窗口将如预期的那样出现,然后放入文件名并保存。一切正常,我将文件放置在确切的位置,并根据需要将文件保存在.txt中,但是当我打开文件时,什么也没有。
我已经测试过书写和打印,但是没有任何效果。所以我想知道我在哪里错了,应该怎么做。
谢谢!
这是我的代码:
jbSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
String path = file.getPath() + ".txt";
file = new File(path);
FileWriter filewriter = new FileWriter(file.getPath(), true);
BufferedWriter buff = new BufferedWriter(filewriter);
PrintWriter writer = new PrintWriter(buff);
writer.write("start");
} catch (FileNotFoundException e2) {
e2.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
答案 0 :(得分:1)
只需向this answer添加更多详细信息或替代方法,就可以使用try-with-resource块,并让JVM为您关闭(并刷新)编写器。
try(PrintWriter writer = ...))
{
writer.write("start");
}
catch (IOException e)
{
// Handle exception.
}
此外,您可以编写实用程序函数来创建PrintWriter:
/**
* Opens the file for writing, creating the file if it doesn't exist. Bytes will
* be written to the end of the file rather than the beginning.
*
* The returned PrintWriter uses a BufferedWriter internally to write text to
* the file in an efficient manner.
*
* @param path
* the path to the file
* @param cs
* the charset to use for encoding
* @return a new PrintWriter
* @throws IOException
* if an I/O error occurs opening or creating the file
* @throws SecurityException
* in the case of the default provider, and a security manager is
* installed, the checkWrite method is invoked to check write access
* to the file
* @see Files#newBufferedWriter(Path, Charset, java.nio.file.OpenOption...)
*/
public static PrintWriter newAppendingPrintWriter(Path path, Charset cs) throws IOException
{
return new PrintWriter(Files.newBufferedWriter(path, cs, CREATE, APPEND, WRITE));
}
如果所有数据都可以在一个操作中写入,则另一种可能性是使用Files.write():
try
{
byte[] bytes = "start".getBytes(StandardCharsets.UTF_8);
Files.write(file.toPath(), bytes)
}
catch (IOException e)
{
// Handle exception.
}
答案 1 :(得分:0)
问题是您没有关闭PrintWriter
实例。完成这样的编写后,只需关闭PrintWriter
即可解决问题:
writer.close();