Skip to content
Advertisement

How To Open File Dialog And Create File On It?

1

I opened File Dialog but I don’t create the file on it? How?

JFileChooser fileChooser = new JFileChooser();
File selectedFile = null;
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(this);
if (**result == JFileChooser.APPROVE_OPTION**) {
    selectedFile = fileChooser.getSelectedFile();
} else {
    confirmExit();
    return;
}

Advertisement

Answer

To save a file with JFileChooser, you need to use the showSaveDialog() method instead of the showOpenDialog() like in your snippet. For more information check out How to use File Choosers and check out the JFileChooser JavaDoc.

Then the next step if the saving has been approved, is to actually write the file. For this, you can use a FileWriter.

I put together a small snippet, which opens a JFileChooser on a button click, where you can provide the filename, where some String will be written to this file.

Example:

public class Test {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> buildGui());
    }

    private static void buildGui() {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        JButton btn = new JButton("Save your File");

        // action listener for the button
        btn.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser(); // create filechooser
            int retVal = fileChooser.showSaveDialog(frame); // open the save dialog
            if (retVal == JFileChooser.APPROVE_OPTION) {    // check for approval
                // create a bufferedwriter with the specified file
                try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile()))) {
                    // write the content to the file
                    writer.write("Your content that shall be written to the file");
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });

        panel.add(btn);
        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}

Output:

enter image description here

enter image description here

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement