Java Swing – JFileChooser example
JFileChooser
is a quick and easy way to prompt the user to choose a file or a file saving location. Below are some simple examples of how to use this class.
JFileChooser
has 6 constructors:
JFileChooser()
– empty constructor that points to user’s default directoryJFileChooser(String)
– uses the given pathJFileChooser(File)
– uses the given File as the pathJFileChooser(FileSystemView)
– uses the given FileSystemViewJFileChooser(String, FileSystemView)
– uses the given path and theFileSystemView
JFileChooser(File, FileSystemView)
– uses the given current directory and theFileSystemView
All the different ways to call the JFileChooser
constructor
//JFileChooser jfc;
//String path = "C:\\Users\\Public";
//File file = new File("C:\\Users\\Public");
//FileSystemView fsv = FileSystemView.getFileSystemView();
//jfc = new JFileChooser();
//jfc = new JFileChooser(path);
//jfc = new JFileChooser(file);
//jfc = new JFileChooser(fsv);
//jfc = new JFileChooser(path, fsv);
//jfc = new JFileChooser(file, fsv);
The writer’s personal preference is to take into account the FileSystemView
. In the examples below we are using FileSystemView.getFileSystemView()
and point it to the home directory through getHomeDirectory()
. That process results into a File type. In other words we are using the constructor JFileChooser(File)
while taking into account the FileSystemView
.
1. show*Dialog() – Open or save a file
Example of how to use the JFileChooser
to get the absolute path for the file the user wants to open or to get the location where the user wants to save the file:
package com.mkyong.jfileChooser;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileSystemView;
public class FileChooser1 {
public static void main(String[] args) {
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
int returnValue = jfc.showOpenDialog(null);
// int returnValue = jfc.showSaveDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = jfc.getSelectedFile();
System.out.println(selectedFile.getAbsolutePath());
}
}
}
Notice that the two methods showOpenDialog()
and showSaveDialog()
are similar, what makes the difference is how the developer handles each one. For readability reasons I wouldn’t suggest mixing the two methods.
Output:
When the user navigates to a directory picks a file and clicks “Open”
Output:
C:\Users\Public\Pictures\pollock.she-wolf.jpg
2. setFileSelectionMode(int) – Select files or directories
With this method we can limit the user to select either Directories only (JFileChooser.DIRECTORIES_ONLY
) or Files only (JFileChooser.FILES_ONLY
) or Files and Directories (JFileChooser.FILES_AND_DIRECTORIES
). The default is FILES_ONLY
. Here’s an example that implements JFileChooser.DIRECTORIES_ONLY
:
package com.mkyong.jfileChooser;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileSystemView;
public class FileChooser2 {
public static void main(String[] args) {
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
jfc.setDialogTitle("Choose a directory to save your file: ");
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnValue = jfc.showSaveDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
if (jfc.getSelectedFile().isDirectory()) {
System.out.println("You selected the directory: " + jfc.getSelectedFile());
}
}
}
}
Output:
You selected the directory: C:\Users\Public\Pictures
3. setMultiSelectionEnabled(Boolean) – Allow multiple selections
An example where multiple selection is enabled. The user picks multiple files and the program prints the names:
package com.mkyong.jfileChooser;
import java.io.File;
import java.util.Arrays;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileSystemView;
public class FileChooser3 {
public static void main(String[] args) {
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
jfc.setDialogTitle("Multiple file and directory selection:");
jfc.setMultiSelectionEnabled(true);
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int returnValue = jfc.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File[] files = jfc.getSelectedFiles();
System.out.println("Directories found\n");
Arrays.asList(files).forEach(x -> {
if (x.isDirectory()) {
System.out.println(x.getName());
}
});
System.out.println("\n- - - - - - - - - - -\n");
System.out.println("Files Found\n");
Arrays.asList(files).forEach(x -> {
if (x.isFile()) {
System.out.println(x.getName());
}
});
}
}
}
Output:
Directories found
Camera Roll
Saved Pictures
- - - - - - - - - - -
Files Found
autumn_rhythm-pollock1.jpg
kuNUfO.jpg
mona.jpg
4. Filters – Limit the set of files shown to the user
It’s always handy to limit user selection to the program’s needs. If for example your program requires png and gif images, it would be good practice to limit the user’s selection to only that. The example below shows how to achieve it using a custom FileNameExtensionFilter
:
package com.mkyong.jfileChooser;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
public class FileChooser4 {
public static void main(String[] args) {
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
jfc.setDialogTitle("Select an image");
jfc.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG and GIF images", "png", "gif");
jfc.addChoosableFileFilter(filter);
int returnValue = jfc.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
System.out.println(jfc.getSelectedFile().getPath());
}
}
}
Output:
As you can see the user is not allowed to pick anything else. The directory shown above contains other types of images too but only gif and png are shown to the user.
The directory looks like this:
5. Use of showDialog()
If you need to customize the approve button, then use the showDialog()
method. Here’s an example of how to use it:
package com.mkyong.inputDialog;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileSystemView;
public class FileChooser5 {
public static void main(String[] args) {
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
jfc.setDialogTitle("Custom button");
int returnValue = jfc.showDialog(null, "A button!");
if (returnValue == JFileChooser.APPROVE_OPTION) {
System.out.println(jfc.getSelectedFile().getPath());
}
}
}
Output:
There is a method in
JFileChooser
called setApproveButtonText(String)
. The problem with this method is that it works only for showOpenDialog()
. It is recommended to use the showDialog()
as a replacement for showSaveDialog()
when a custom button is needed.
You should also check the simplest and most common-used methods to write and read files:
This was very helpful. Thanks!
thanks a lot
Really a good Post, Thank you very much, it has been very useful to me!
thank you so much for this nice post.
it is very helpful.
Perfect!!!
how to search any element in the file using gui
Hi MK,
I have one query related this Java Swing.
I want to edit my local directory while running Java Swing application. Details is i have a folder tree structure in my application where i am trying to edit these folder or rename this folder in UI as well as backend also. So Can you please help me on this issue.
When i check my code that time its calling this rename method but its returning me false.
I have a FileUtils class where i have created a method for this rename() which is also calling this method but returning false.
Please help me this issue.
Thanks & Regards
Sailendra Narayan Jena
Thanks so much! It’s very helpful.
Finally some quality content!
Thank you Marilena.
How to display last access directory in dialog box?
Thanks for this tut, perfect…
thx i was refreshing my java Filechooser
Application hangs while using on mac OSX
…
Does not seem to work on Oxygen 2.0. Is there anything that should be done differently?
arigato gosaimasu <3