Created
April 24, 2012 17:42
-
-
Save chrishuan9/2481881 to your computer and use it in GitHub Desktop.
Search specific string in a text file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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