문제

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 :

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.

도움이 되었습니까?

해결책 2

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.

Try adding this to your try block:

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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top