Skip to content

Instantly share code, notes, and snippets.

@chrishuan9
Created April 24, 2012 17:42
Show Gist options
  • Save chrishuan9/2481881 to your computer and use it in GitHub Desktop.
Save chrishuan9/2481881 to your computer and use it in GitHub Desktop.
Search specific string in a text file
//Using a Scanner makes it easy to search a text file for a string in Java. You can find the code HERE
import java.io.*;
import java.util.Scanner;
public class FileSearch {
public static void main(String[] args) {
// Testing only
File f = new File(args[0]);
String search = args[1];
System.out.printf("Result of searching for %s in %s was %b\n", search, f.getName(), FileSearch.find(f, search));
}
public static boolean find(File f, String searchString) {
boolean result = false;
Scanner in = null;
try {
in = new Scanner(new FileReader(f));
while(in.hasNextLine() && !result) {
result = in.nextLine().indexOf(searchString) >= 0;
}
}
catch(IOException e) {
e.printStackTrace();
}
finally {
try { in.close() ; } catch(Exception e) { /* ignore */ }
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment