Home Tutorial Java Core Files Java File Chooser

 
 

Share on Google+Share on Google+
Java File Chooser
Posted on: April 14, 2006 at 12:00 AM
Advertisement
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
Advertisement

Related Tags for Java File Chooser:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 14, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com