// File: Fields0.java import java.io.*; /** Demonstrate the ability to scan a file, find a part of the file * and extract and store unique fields from the file. Also shows * documentation in javadoc form. * * @author David G. Green */ public class Fields0 { /** known fields */ static String [] fields = new String[100]; /** number of known fields */ static int n_fields = 0; // number of fields /** buffered input stream to file */ static BufferedReader in = null; // definitions of the markers static final String BEGIN_RECORD_TAG = ""; static final String END_RECORD_TAG = ""; /** main program */ public static void main ( String[] args ) throws IOException { System.out.println("Fields"); // Open File try { in = new BufferedReader ( new FileReader("test.txt") ); } catch ( FileNotFoundException ex ) { System.out.println("Could not open test.txt"); // bail out return; } // process file finding a record, processing till no more records while( true ) { // Find start of record if (! seekStartOfRecord() ) // none break; // Discover fields in this record updateFields(); } // Print fields printFields(); } /** seek the start of a record in the input stream * * @returns whether or not start of record is found */ public static boolean seekStartOfRecord() throws IOException { String line; while ( true ) { // read line line = getLine(); if ( line == null ) return false; // hit EOF // return when we have read the beginning of the record if ( line.equals(BEGIN_RECORD_TAG) ) return true; // else keep reading } } /** get a line from the input stream */ public static String getLine() throws IOException { return in.readLine(); } /** read the current record, extract the field, and update the list * of known fields */ public static void updateFields() throws IOException { String line; String a_field; while ( true ) { // read a line, quit at end of record // bug: don't handle "early" EOF line = getLine(); if ( line.equals(END_RECORD_TAG) ) break; // extract field a_field = line.substring(0,line.indexOf("=")); // if field not there, then add it if ( findField( a_field ) == -1 ) { fields[n_fields]=a_field; n_fields++; } } } /** print out the known fields */ public static void printFields() { System.out.println("Discovered Fields"); if ( n_fields == 0 ) System.out.println( "(none)"); else { for (int i=0; i < n_fields; i++ ) System.out.println( fields[i] ); } } /** try to find a field in the list of known fields * * @param fld - the field to try to find * @returns index into list if found or -1 if not found */ public static int findField( String fld) { for ( int i = 0; i < n_fields; i++ ) { if ( fields[i].equals( fld ) ) return i; } // if not found, return -1 return -1; } }