Home Tutorial Java Core Files Java file browse

 
 

Java file browse
Posted on: April 14, 2006 at 12:00 AM
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.

Related Tags for Java file browse:


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.