import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; /** * * @author gtowell * File: TokenFinder.java * Desc: Class to to wrap a method that searches for a token in a file that is * split by a given character */ public class TokenFinder { /** * The filename to search in */ private String filename; /** * The thing on which to split. */ private String splitter; /** * The token to look for */ private String target; /** * Constructor. Just takes and stores the parameters * @param fName the file to be searched * @param split the thing on which to split lines. Usually a single character, but can be any string * @param targt the thing to look for after splitting lines */ public TokenFinder(String fName, String split, String targt) { this.filename=fName; this.splitter=split; this.target=targt; } /** * Actually do the work. * @return an integer of the form 10000*lineNumber + token Number */ public int doWork() { if (this.filename==null || this.splitter==null || this.splitter==null) { return 0; } int lineNumber=0; Scanner fileScanner=null; try { fileScanner = new Scanner(new File(this.filename)); while(fileScanner.hasNextLine()) { String line = fileScanner.nextLine(); lineNumber++; Scanner lineScanner = new Scanner(line); lineScanner.useDelimiter(this.splitter); int tokenNumber=0; while (lineScanner.hasNext()) { String linePart=lineScanner.next(); tokenNumber++; System.out.println(lineNumber + " " + tokenNumber + " " + linePart); if (linePart.equals(this.target)) { lineScanner.close(); return lineNumber*10000+tokenNumber; } } lineScanner.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (fileScanner!=null) fileScanner.close(); } return 0; } }