In this section, you will learn how to browse the file system.
In this section, you will learn how to browse the file system.In this section, you will learn how to browse the file system.
Description of code
Swing provides various useful classes and methods. It has provide this utility too by introducing the class JFileChooser. Through the use of this class, you can browse the file system and can select the file. This is the easiest way of selecting the file from the file system. 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 f = chooser.getSelectedFile(); String filename = f.getName(); System.out.println("You have chosen: " + filename); } }
Through the use of JFileChooser class, you can browse the file system and can select the file of your choice.