Java Notes
Using JFileChooser
[Note: Needs more explanations.]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
// File : intro/dialog/FileChooserDemo.java // Purpose: Show how to use JFileChooser without a full GUI. // Author : Fred Swartz - 2006-11-14 import java.io.*; import javax.swing.*; import java.util.*; public class FileChooserDemo { public static void main(String[] args) { //... Create a file chooser. JFileChooser chooser = new JFileChooser(); //... Display it to the user. int retval = chooser.showOpenDialog(null); //... Check to see if the user selected a file. if (retval == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); // Get selected file. //... Enclose in try..catch because file might not be readable. try { Scanner in = new Scanner(file); // Create a scanner //... These next two lines are just a sample use. // Replace this with what you would like to do. String firstLine = in.nextLine(); JOptionPane.showMessageDialog(null, firstLine); } catch (IOException ex) { //... Something went wrong with trying to read // the file. For example, there was no permission, // or maybe it was locked by another program, or ... JOptionPane.showMessageDialog(null, "Can't read file?"); } } } } |