Home > Back-end >  how do you return a boolean for if scanner finds a specified string within a file?
how do you return a boolean for if scanner finds a specified string within a file?

Time:08-16

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;
        }
    }

CodePudding user response:

I would use a while-loop and simply use indexOf to compare the currentLine to your string.

public boolean findString(File f, String s) throws FileNotFoundException {
    Scanner scan = new Scanner(f);
    String currentLine;

    while((currentLine = scanner.readLine()) != null) {
      if(currentLine.indexOf(s)) {        
         return true;
      }
    }

    return false;
} 

An advantage of doing it this way is that you can also have an integer which you increase with every run of the loop to get the line in which the string is included (if you want/need to).

CodePudding user response:

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;
}
  •  Tags:  
  • java
  • Related