简体   繁体   English

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

[英]How to save a file using JFileChooser.showSaveDialog?

I am making a text editor in Java and my save function doesnt work the way i want it to. 我正在用Java创建一个文本编辑器,我的保存功能并不像我想要的那样工作。 here is the code i use to save a file : 这是我用来保存文件的代码:

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. 单击“保存”后,再次打开窗口并保存到Eclipse Workspce。 I googled the internet and nobody had the same problem. 我用Google搜索互联网,没有人遇到同样的问题。

I think the problem is that you never take the selected file . 我认为问题是你永远不会选择所选文件 You just setSelectedFile on a file created after a hardcoded name. 您只需在硬编码名称后创建的文件上设置SelectedFile。 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. 实际上,您要写入的文件是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));

It's because you wrote: 这是因为你写道:

savefile.showSaveDialog(savefile); 

And also: 并且:

 int sf = savefile.showSaveDialog(null);

( Twice ). 两次 )。 You just need to delete: 你只需要删除:

savefile.showSaveDialog(savefile);

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

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