I am just learning that language and was wondering what a more experience Java programmer would do in the following situation?
I would like to create a java program that will search a specified file for all instanced for a specific word.
How would you go about this, does that Java API come with a class that provides file scanning capabilities or would i have to write my own class to do this?
Thanks for any input,
Dom.
The java API does offer the java.util.Scannerclass which will allow you to scan across an input file.
Depending on how you intend to use this, however, this might not be the best idea. Is the file very large? Are you searching only one file or are you trying to keep a database of many files and search for files within that? In that case, you might want to use a more fleshed out engine such as lucene.
Unless the file is very large, I would
String text = IOUtils.toString(new FileReader(filename));
boolean foundWord = text.matches("\\b" + word+ "\\b");
To find all the text between your word you can use split() and use the length of the strings to determine the position.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With