/* File: im.java index maker yanushka */ import java.io.*; import java.util.*; import java.text.*; /** The class IndexMaker builds an index for a text file. It is based on the class IndexGenerator of Koffman and Wolfgang. */ class IndexMaker { private final static int WORD_WIDTH = 30, LINE_NUM_WIDTH = 3; private final static String NL = "\n", DELIMITERS = "\\p{Punct}+|\\p{Blank}+", ORDER_FORMAT = "%s %" + LINE_NUM_WIDTH + "s", PRINT_FORMAT = "%" + WORD_WIDTH + "s %" + LINE_NUM_WIDTH + "s", SPACE_REGEX = "\\s+"; private TreeSet< String > index; /* Create an IndexMaker object. */ public IndexMaker() { index = new TreeSet < String > (); } /* Create an IndexMaker object and fill it from a text file. @param fileName, the name of a text file */ public IndexMaker( String fileName ) { this(); buildIndex( fileName ); } /** buildIndex() fills an index from a text file. Read each word in text file fielName and store it in the search tree along with its line number. post: lowercase form of each word with its line number occurs in index. @param fileName, the name of a text file */ public void buildIndex( String fileName ) { try { Scanner sc = new Scanner( new File( fileName ) ), lSc; int lineNum = 0; String nextLine, token; // Read a line. while ( sc.hasNextLine() ) { lineNum++; nextLine = sc.nextLine(); // Parse nextLine. lSc = new Scanner( nextLine ); lSc.useDelimiter( DELIMITERS ); while ( lSc.hasNext() ) { token = lSc.next().toLowerCase(); if ( token.length() > 0 ) index.add( String.format( ORDER_FORMAT, token, lineNum ) ); } } } catch( FileNotFoundException ie ) { ie.printStackTrace(); } } /** Use an iterator for a TreeSet object to return a string with one item of the index per line. @return a String representation of index */ public String toString() { String ans = ""; String [] pair; // Use an iterator to access and display tree data. for ( String next : index ) { pair = next.split( SPACE_REGEX ); ans += String.format( PRINT_FORMAT, pair[ 0 ], pair[ 1 ] ) + NL; } return ans; } } /** The class Test creates and displays an index for a text file. */ class Test { private final static String DEFAULT_FILE = "im.java"; public static void main( String [] args ) { if ( args.length == 0 ) System.out.println( new IndexMaker( DEFAULT_FILE ) ); else System.out.println( new IndexMaker( args[ 0 ] ) ); } }