Home Tutorial Java Core Files Java File Chooser

 
 

Java File Chooser
Posted on: April 14, 2006 at 12:00 AM
In this section, you will learn how to select a file from the file system.

Java File Chooser

Java provides javax.swing.* package that is really a beneficial one. It provides several useful classes which can be used for different purposes. Among them, JFileChooser is a standard dialog for selecting a file from the file system. This has made the user to select file or directory of their choice easily. Here we have used this class to select the file and pass it to the File object. The method getName() of File returns the name of the file.

getSelectedFile()- This method of JFileChooser class returns the selected file.

getName()- This method of File class returns the file name from the path.

Here is the code:

import java.io.*;
import javax.swing.*;

public class FileChooser {
	public static void main(String[] args) {
		JFileChooser chooser = new JFileChooser();
		chooser.showOpenDialog(null);
		File f = chooser.getSelectedFile();
		String filename = f.getName();
		System.out.println("You have selected: " + filename);
	}
}

In the above code, JFileChooser class provides the ability to select a particular file from the file system. 

Output:

On clicking the 'open' button, the selected file name will get displayed on the console:

You have selected: input.txt

Related Tags for Java File Chooser:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.