Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how do you return a boolean for if scanner finds a specified string within a file?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading