用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();

            }

        }       

    }           

});


慕丝7291255
浏览 204回答 2
2回答

智慧大石

问题是您没有关闭PrintWriter实例。您可以通过PrintWriter在完成这样的编写后关闭来解决您的问题:writer.close();

交互式爱情

只是为该答案添加更多详细信息或替代方法,您可以使用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.}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java