// FileChooserDemo.java // Reads text from a file, and prints each word on a separate line // A version of FileInputDemo that uses a FileChooser // cmc, 11/17/05 import java.io.IOException; import java.util.Scanner; import javax.swing.JFileChooser; public class FileChooserDemo { public static void main (String args[]) { Scanner input = null; // try to open the file try { JFileChooser chooser = new JFileChooser(); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) input = new Scanner( chooser.getSelectedFile() ); } catch (IOException e) { System.err.println("could not open file - " + e); System.exit(1); } // got a Scanner now (it handles the IOExceptions from now on ;-) // loop through the tokens in the file and print one per line while ( input.hasNext() ) System.out.println( input.next() ); System.exit(0); // might be necessary due to use of dialog box } }