简体   繁体   English

无法使用Java中的JFileChooser保存文件

[英]File not saved using JFileChooser in Java

Iam a java beginner. 我是Java初学者。 I have written a simple program to write some contents to a file using showSaveDialoge() in JFileChooser. 我编写了一个简单的程序,使用JFileChooser中的showSaveDialoge()将一些内容写入文件。 The code including below. 该代码包括以下内容。

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.");
        }
    }

the code gets executed and Save Dialogue box has come. 代码被执行,“保存对话”框到了。 But when I click SAVE button on Dialogue box, nothing had happening. 但是,当我单击“对话框”上的“保存”按钮时,什么都没有发生。 The file has not saved in the selected location. 该文件尚未保存在所选位置。 What may be the reason.? 可能是什么原因? Thanks in advance. 提前致谢。

What is hapenning is: 发生什么现象是:

you create a File in your current location with name fileName.txt 您在当前位置创建一个文件,文件名为fileName.txt

File file = new File("fileName.txt"); //could be $HOME$/fileName.txt

User selects ProgramFiles/file.txt 用户选择ProgramFiles / file.txt

but you uses on FileWritter file information, not what user chossed from FileChooser. 但是您使用的是FileWritter的文件信息,而不是用户从FileChooser选择的信息。

change 更改

FileWriter writer = new FileWriter(file);  

to

FileWriter writer = new FileWriter(chooser.getSelectedFile());

Try this: 尝试这个:

            FileWriter writer = new FileWriter(fc.getSelectedFile());

It should write to selected file from file chooser. 它应从文件选择器写入所选文件。

You were writing to fileName.txt which will be saved in current directory from which you run program. 您正在写入fileName.txt,它将保存在运行程序的当前目录中。

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

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