Main Tutorials

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 directory
  • JFileChooser(String) – uses the given path
  • JFileChooser(File) – uses the given File as the path
  • JFileChooser(FileSystemView) – uses the given FileSystemView
  • JFileChooser(String, FileSystemView) – uses the given path and the FileSystemView
  • JFileChooser(File, FileSystemView) – uses the given current directory and the FileSystemView

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:

FileChooser1.java

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:

swing-jfilechooser-4a

When the user navigates to a directory picks a file and clicks “Open”

swing-jfilechooser-4b

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:

FileChooser2.java

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:

swing-jfilechooser-4c

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:

FileChooser3.java

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:

swing-jfilechooser-4d

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:

FileChooser4.java

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:

swing-jfilechooser-4e

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:

swing-jfilechooser-4f

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:

FileChooser5.java

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:

swing-jfilechooser-4g
Note
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:

References

  1. JFileChooser – Java 8 API
  2. FileSystemView – Java 8 API
  3. FileNameExtension – Java 8 API

About Author

author image
Marilena Panagiotidou is a senior at University of the Aegean, in the department of Information and Communication Systems Engineering. She is passionate about programming in a wide range of languages. You can contact her at [email protected] or through her LinkedIn.

Comments

Subscribe
Notify of
16 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Tom
3 years ago

This was very helpful. Thanks!

Kim
5 years ago

thanks a lot

Paul
6 years ago

Really a good Post, Thank you very much, it has been very useful to me!

anurag
6 years ago

thank you so much for this nice post.
it is very helpful.

Raphael dos Anjos
1 year ago

Perfect!!!

rohith
4 years ago

how to search any element in the file using gui

Sailendra Narayan Jena
4 years ago

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

Abdoulrachid
4 years ago

Thanks so much! It’s very helpful.

Jair
4 years ago

Finally some quality content!
Thank you Marilena.

Deepak
4 years ago

How to display last access directory in dialog box?

Fábio Baziota
4 years ago

Thanks for this tut, perfect…

Francis Gagnon
5 years ago

thx i was refreshing my java Filechooser

Rubina
5 years ago

Application hangs while using on mac OSX

asdgfadf
3 years ago
Reply to  Rubina

Tanvir
5 years ago

Does not seem to work on Oxygen 2.0. Is there anything that should be done differently?

ziad El Khomssi
5 years ago

arigato gosaimasu <3