
Untitled
By: a guest on
Aug 3rd, 2012 | syntax:
None | size: 1.26 KB | hits: 7 | expires: Never
//Search the data file for q
public static void searchFile(String q, String fileName){
try {
FileInputStream fstream = new FileInputStream(fileName);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
System.out.println("\nSearching file for " + q + "...\n");
while ((line = br.readLine()) != null) {
if (testWord(line, q)){
outputSearchMatches(line); //output when match is found
}
System.out.println("\n");
}
} catch (IOException e){
System.out.println("IO Error Occured: " + e.toString());
}
}
//Outputs each match found while searching the data file
public static void outputSearchMatches(String line) {
StringTokenizer stk = new StringTokenizer(line, " ");
while (stk.hasMoreTokens()){
System.out.print(stk.nextToken() + " ");
}
}
//method testWord tests to see if the line contains the word being searched
public static boolean testWord(String testLine, String testw){
String word ="";
try {
Scanner myScanner = new Scanner(testLine);
while (myScanner.hasNext()){
word = myScanner.next();
if (testw.equals(word)){
return true;
}
}
} catch (Exception error){}
return false;
}