Java show save file dialog using jfilechooser

www.i‮ig‬ftidea.com

In Java Swing, you can use the JFileChooser component to display a "Save" dialog to the user and allow them to select a location to save a file. Here's an example of how to do this:

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.filechooser.FileNameExtensionFilter;

public class SaveFileDialogExample extends JFrame {

    public SaveFileDialogExample() {
        super("Save File Dialog Example");

        // Create a new file chooser
        JFileChooser fileChooser = new JFileChooser();

        // Set the file chooser to display only files with the .txt extension
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
        fileChooser.setFileFilter(filter);

        // Display the "Save" dialog
        int result = fileChooser.showSaveDialog(this);

        // If the user clicked "Save"
        if (result == JFileChooser.APPROVE_OPTION) {
            // Get the selected file
            java.io.File file = fileChooser.getSelectedFile();

            // Do something with the file, like writing to it
            // ...

            System.out.println("Selected file: " + file.getAbsolutePath());
        }

        // Set the size, location and visibility of the frame
        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new SaveFileDialogExample();
    }
}

In this example, we create a JFileChooser component and set its file filter to allow only files with the .txt extension. We then display the "Save" dialog using the showSaveDialog method and wait for the user to select a file. If the user clicks "Save", we retrieve the selected file using the getSelectedFile method and do something with it, like writing to it.

Note that the showSaveDialog method is a blocking call, so the code after it won't be executed until the user selects a file or cancels the dialog.

When you run this example, a "Save" dialog will be displayed to the user, and they will be able to select a location to save a file. If they select a file and click "Save", the file's path will be printed to the console. If they cancel the dialog, nothing will happen.