Swing provides class javax.swing.JFileChooser that can be used to present a dialog for user to choose a location and type a file name to be saved, using showSaveDialog() method. Syntax of this method is as follows:

        public int showSaveDialog(Component parent)

 

where parentis the parent component of the dialog, such as a JFrame. Once the user typed a file name and select OK or Cancel, the method returns one of the following value:

    • JFileChooser.CANCEL_OPTION : the user cancels file selection.
    • JFileChooser.APPROVE_OPTION: the user accepts file selection.
    • JFileChooser.ERROR_OPTION: if there’s an error or the user closes the dialog by clicking on X button.

After the dialog is dismissed and the user approved a selection, use the following methods to get the selected file:

    • FilegetSelectedFile()

Before calling showSaveDialog() method, you may want to set some options for the dialog:

    • setDialogTitle(String) sets a custom title text for the dialog.
    • setCurrentDirectory(File) sets the directory where will be saved.

Following is an example code:

// parent component of the dialog
JFrame parentFrame = new JFrame();

JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Specify a file to save");    

int userSelection = fileChooser.showSaveDialog(parentFrame);

if (userSelection == JFileChooser.APPROVE_OPTION) {
    File fileToSave = fileChooser.getSelectedFile();
    System.out.println("Save as file: " + fileToSave.getAbsolutePath());
}

And following is a screenshot of the dialog:

save file dialog

You can download a fully working example code in the attachment section.

 

Related Swing File Chooser Tutorials:

 

Other Java Swing Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Attachments:
Download this file (SaveFileDialogExample.java)SaveFileDialogExample.java[source code]1 kB

Add comment

   


Comments 

#25arda2020-10-28 06:33
nice good...............
Quote
#24Kamlesh Bagul2019-04-15 08:07
Working Fine thank..............
Quote
#23BatuhanSubasi2017-08-04 07:13
Hello
I want to save my file. For example ;
///////////////////////////////////////////////////////////////////////////////
File delFile4= new File("C:\\Users\\Batuhan\\Desktop\\BiletArsivi.zip");
////////////////////////////////////////////////////////////////////////////////
this is my file and ı want to save , user want to where select pathadress.
sorry my englısh but you can help me
Quote
#22mathan2017-03-13 23:27
thankyou for sharing.
Quote
#21aaa2016-04-03 07:55
C:\Users\hp\Desktop\NotePro123.java:149: showOpenDialog(java.awt.Component) in javax.swing.JFileChooser cannot be applied to (NotePro123)


how can it be error when awt components can work in swing ??
Quote