/* * FileExample.java * * Created on February 26, 2004, 5:19 PM */ package datamining; // for files import java.io.File; import java.io.*; // for FileChooser import javax.swing.*; import java.awt.Container; // for breaking strings up into parts import java.util.StringTokenizer; /** * * @author redmond */ public class FileExample { /** Creates a new instance of FileExample */ public FileExample() { } /** * get started with a file - including choosing it using the FileChooser, * making sure we can read from it */ public static BufferedReader startFile () throws IOException { ////////////////////////////// // set up for reading file ////////////////////////////// // for using FileChooser JFrame empty = new JFrame(); // just create as GUI container so can use file chooser Container dummy = empty.getContentPane(); JFileChooser files; // for using text files File filehandle; FileReader fReader; BufferedReader bReader; /// For the FileChooser approach empty.setVisible(true); // display empty JFrame files = new JFileChooser(); // start open file dialog box int result = files.showOpenDialog(dummy); if (result == 0) { // if successful, read the file filehandle = files.getSelectedFile(); // check if can read if (filehandle.exists() && filehandle.canRead() ) { // prepare to read it fReader = new FileReader(filehandle); bReader = new BufferedReader(fReader); } else { throw new IOException(); // signal that we are unable to handle the file } } else { throw new IOException(); // signal that we are unable to handle the file } return bReader; } // demonstrate breaking line into parts public static void demoTokenization(String inputLine) { StringTokenizer tokenizer; // for breaking line of text down into parts // take care of the data in this record tokenizer = new StringTokenizer(inputLine,",{}"); while (tokenizer.hasMoreTokens()) { String part = tokenizer.nextToken(); System.out.println(" token: " + part); } return; } /** * @param args the command line arguments */ public static void main(String[] args) { String line; // for reading a line of a file into BufferedReader bReader = null; // for getting input from - /// everything else in the set up is hidden from the programmer after this // get set to read try { // select file and prepare to read bReader = startFile(); // just read junk line = bReader.readLine(); // read until end of file while (line != null) { // just echo input file System.out.println("line: " + line); // just to demonstrate - break line into its parts // no return - just display to console (because this program // doesn't actually do anything with the input) demoTokenization(line); line = bReader.readLine(); } } catch (IOException ex) { System.out.println("Read failed. Exiting ...'"); System.exit(0); } } }