In this section, you will learn how to browse a file and allows the user to choose a file.
In this section, you will learn how to browse a file and allows the user to choose a file.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.