简体   繁体   中英

File not saved using JFileChooser in Java

Iam a java beginner. I have written a simple program to write some contents to a file using showSaveDialoge() in JFileChooser. 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

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

User selects ProgramFiles/file.txt

but you uses on FileWritter file information, not what user chossed from 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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