Java I/O 05. GUI File chooser

Опубликовано: 24 Март 2026
на канале: Snipcademy
1,162
4

This video tutorial will show you how to create a GUI so that the user may choose a file.

The following code may have been modified to meet Youtube's guidelines. Please go to    • Java I/O 00. Input/Output Basics Setup   to download the actual file.

/**
GUI File Chooser
You can also have the user choose a file through a GUI
This GUI is from javax.swing.JFileChooser
**/

import javax.swing.JFileChooser;
import java.util.Scanner;
import java.io.File;

public class GUIFileChooser {

public static void main(String[] args) throws Exception {

JFileChooser fileChooser = new JFileChooser();

if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File openedFile = fileChooser.getSelectedFile();

Scanner in = new Scanner(openedFile);

System.out.println("Printing contents of the chosen file: ");

while(in.hasNext()) {
System.out.println(in.nextLine());
}

in.close();

} else {

System.out.println("File not selected");
System.exit(1);

}
}

}