Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 3rd, 2012  |  syntax: None  |  size: 1.26 KB  |  hits: 7  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. //Search the data file for q
  2. public static void searchFile(String q, String fileName){
  3.                 try {
  4.                         FileInputStream fstream = new FileInputStream(fileName);
  5.                         DataInputStream in = new DataInputStream(fstream);
  6.                         BufferedReader br = new BufferedReader(new InputStreamReader(in));
  7.                         String line;
  8.                        
  9.                         System.out.println("\nSearching file for " + q + "...\n");
  10.                        
  11.                         while ((line = br.readLine()) != null) {
  12.                                 if (testWord(line, q)){
  13.                                         outputSearchMatches(line);  //output when match is found
  14.  
  15.                                 }
  16.                                 System.out.println("\n");
  17.                         }
  18.                        
  19.                 } catch (IOException e){
  20.                         System.out.println("IO Error Occured: " + e.toString());
  21.                 }
  22.         }
  23.        
  24.         //Outputs each match found while searching the data file
  25.         public static void outputSearchMatches(String line) {
  26.                 StringTokenizer stk = new StringTokenizer(line, " ");
  27.                 while (stk.hasMoreTokens()){
  28.                         System.out.print(stk.nextToken() + " ");
  29.                 }
  30.         }
  31.        
  32.         //method testWord tests to see if the line contains the word being searched
  33.         public static boolean testWord(String testLine, String testw){
  34.                
  35.                 String word ="";
  36.                
  37.                 try {
  38.                         Scanner myScanner = new Scanner(testLine);
  39.                        
  40.                         while (myScanner.hasNext()){
  41.                                 word = myScanner.next();
  42.                                
  43.                                 if (testw.equals(word)){
  44.                                         return true;
  45.                                 }
  46.                         }
  47.                 } catch (Exception error){}
  48.                
  49.                 return false;
  50.         }