在Java中使用JFileChooser保存文件

Saj*_*eev 1 java swing jfilechooser file filepath

我是一名java初学者.我编写了一个简单的程序,使用JFileChooser中的showSaveDialoge()将一些内容写入文件.代码包括以下内容.

public static void main(String arg[]) throws IOException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
    {   
        JFrame frame = new JFrame();
        JFileChooser fc = new JFileChooser();   
        try {
            File file = new File("fileName.txt");
            fc.setSelectedFile(file);
            int r = fc.showSaveDialog(frame);   
            if(r == JFileChooser.APPROVE_OPTION)
            {   
                FileWriter writer = new FileWriter(file);   
                writer.append("Data inside the file");
                writer.flush();
                writer.close();
            }
            else if(r == JFileChooser.CANCEL_OPTION) {
                System.out.println("Do nothing for CANCEL");
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "File could not be written, try again.");
        }
    }
Run Code Online (Sandbox Code Playgroud)

代码被执行并且保存对话框已经到来.但是当我点击对话框上的SAVE按钮时,什么也没发生.该文件尚未保存在所选位置.可能是什么原因.?提前致谢.

Ram*_*oza 6

什么是hapenning是:

您在当前位置创建名为fileName.txt的文件

File file = new File("fileName.txt"); //could be $HOME$/fileName.txt
Run Code Online (Sandbox Code Playgroud)

用户选择ProgramFiles/file.txt

但是你使用FileWritter文件信息,而不是从FileChooser中扔出的用户.

更改

FileWriter writer = new FileWriter(file);  
Run Code Online (Sandbox Code Playgroud)

FileWriter writer = new FileWriter(chooser.getSelectedFile());
Run Code Online (Sandbox Code Playgroud)