繁体   English   中英

用JFileChooser写入文件

[英]Write into a file with JFileChooser

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

只是为该答案添加更多详细信息或替代方法,您可以使用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.
}

问题是您没有关闭PrintWriter实例。 完成这样的编写后,只需关闭PrintWriter即可解决问题:

writer.close();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM