Java 如何使用 JFileChooser.showSaveDialog 保存文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22261130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:35:45  来源:igfitidea点击:

How to save a file using JFileChooser.showSaveDialog?

javaeclipsetexttext-editornotepad

提问by Thor

I am making a text editor in Java and my save function doesnt work the way i want it to. here is the code i use to save a file :

我正在用 Java 制作一个文本编辑器,但我的保存功能没有按照我想要的方式工作。这是我用来保存文件的代码:

public void actionPerformed(ActionEvent event) {
        String filename = JOptionPane.showInputDialog("Name this file");
        JFileChooser savefile = new JFileChooser();
        savefile.setSelectedFile(new File(filename));
        savefile.showSaveDialog(savefile);
        BufferedWriter writer;
        int sf = savefile.showSaveDialog(null);
        if(sf == JFileChooser.APPROVE_OPTION){
            try {
                writer = new BufferedWriter(new FileWriter(filename,
                        false));
                text.write(writer);
                writer.close();
                JOptionPane.showMessageDialog(null, "File has been saved","File Saved",JOptionPane.INFORMATION_MESSAGE);
                // true for rewrite, false for override

            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if(sf == JFileChooser.CANCEL_OPTION){
            JOptionPane.showMessageDialog(null, "File save has been canceled");
        }
    }

When i click the save button the window pops up and i choose where i want to save it. After i click save it opens up the window again and saves to my Eclipse Workspce. I googled the internet and nobody had the same problem.

当我单击保存按钮时,会弹出窗口,然后我选择要保存的位置。单击保存后,它会再次打开窗口并保存到我的 Eclipse Workspce。我用谷歌搜索互联网,没有人遇到同样的问题。

采纳答案by egelev

I think the problem is that you never take the selected file. You just setSelectedFile on a file created after a hardcoded name. After that you instantiate a writer on those file but the problem is that the chosen file is not taken. Actually the file you are writting to is File(filename) which is created in the project's root directory.

我认为问题在于您从不采取选定的文件。您只需在硬编码名称后创建的文件上设置SelectedFile。之后,您在这些文件上实例化一个编写器,但问题是未采用所选文件。实际上,您要写入的文件是在项目根目录中创建的 File(filename)。

Try adding this to your try block:

尝试将其添加到您的 try 块中:

writer = new BufferedWriter(new FileWriter(saveFile.getSelectedFile()));

insted of this:

这样做的:

writer = new BufferedWriter(new FileWriter(filename,
                    false));

回答by unnammed

It's because you wrote:

那是因为你写道:

savefile.showSaveDialog(savefile); 

And also:

并且:

 int sf = savefile.showSaveDialog(null);

(Twice). You just need to delete:

两次)。你只需要删除:

savefile.showSaveDialog(savefile);