I’m not very familiar with File & Scanner objects so please bear with me:
I’m attempting to have a scanner look through a file and see if a specific string exists, then return true/false – I thought there would be a method for this but either I’m reading the docs wrong or it doesn’t exist.
What I’m able to come up with is the following but I’m sure there’s a simpler way.
public boolean findString(File f, String s) throws FileNotFoundException {
Scanner scan = new Scanner(f);
if(scan.findWithinHorizon(s, 0) != null) {
return true;
} else {
return false;
}
}
>Solution :
Well, there are many ways to check whether a certain file contains a certain string, but I can’t think of a single method which opens the file, scans for the given pattern and then returns a boolean indicating whether the pattern has been found within the file.
I think that use-case would be to small, as in many cases, you want to do more with the contents than only searching whether it contains a specific pattern. Often you want to process the file contents.
Regarding your code, it is already fairly short. However, I would change two things here. First, as scan.findWithinHorizon(s, 0) != null already is a boolean expression, you could immediately return it, instead of using if-else. Second, you should close the file you opened. You can use the try-with-resources construct for this.
Here is the updated code:
try (Scanner scan = new Scanner(f)) {
return scan.findWithinHorizon(s, 0) != null;
}
-
More on finding a pattern in a file: this Stack Overflow post
-
More on try-with-resources: Oracle Java documentation, Baeldung
-
Alternative code to find a pattern within a file:
return Pattern.compile(s) .matcher(Files.readString(f.toPath())) .find();