gpt4 book ai didi

java - 使用 JFileChooser 写入文件

转载 作者:行者123 更新时间:2023-12-02 11:05:01 25 4
gpt4 key购买 nike

我尝试在单击按钮时使用 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();
}
}
}
});

最佳答案

只是为了添加更多详细信息或替代方案 this answer ,您可以使用 try-with-resource block 并让 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.
}

关于java - 使用 JFileChooser 写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51046195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com