Share on Google+Share on Google+

Java file browse

Advertisement
In this section, you will learn how to browse a file and allows the user to choose a file.

Java file browse

In this section, you will learn how to browse a file and allows the user to choose a file.

Description of code

GUI provide File choosers for navigating the file system, and then provide the utility to choose either file or directory from a list. The JFileChooser class opens up a file browser window and allows the user to choose a file.  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.

showOpenDialog()- This method of JFileChooser class open the dialog and allow to select 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 FileBrowser {
	public static void main(String[] args) {
		JFileChooser chooser = new JFileChooser();
		chooser.showOpenDialog(null);
		File file = chooser.getSelectedFile();
		String filename = file.getName();
		System.out.println("You have selected: " + filename);
	}
}

Through the use of JFileChooser class, you can navogate the file system and can select the file or directory of your choce.

Advertisements

Posted on: April 14, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.