Search code examples
javacompilationmatcher

How to pass a file into Java Matcher?


I have this simple method that uses Java Matcher

public int countWord(String word, File file) throws FileNotFoundException {

    String patternString = word;
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(file);

    int count = 0;
    while (matcher.find()) {
        count++;
        System.out.println("found: " + count + " : "
                + matcher.start() + " - " + matcher.end());
    }
    return  count;
}

My idea is to pass a file into the instruction:

Matcher matcher = pattern.matcher(file);

but Java complains it even if I follow the advice of the IDE that said to do a cast like this:

java.util.regex.Matcher matcher = pattern.matcher((CharSequence) file);

In fact when I try to launch the compilation it reports this message:

Exception in thread "main" java.lang.ClassCastException: java.io.File cannot be cast to java.lang.CharSequence

How can I pass this obstacle?


Solution

  • Of course you cannot cast a File to CharSequence, they have nothing to do with each other.

    Method matcher in the Pattern class accepts a CharSequence argument, so you need to pass a CharSequence (most likely a String) to it.

    You need to read contents of the file. There is a lot of methods and it all depends if you know if your file is big or small. If it's small then you can just read all lines, collect them into a single String and pass it to the matcher method. If it's big then you can't read it all at once (you would consume a lot of memory) so you need to read it in chunks.

    Considering that you need to look through the contents and find a specific pattern, this may be difficult - let's say your pattern is longer than a single chunk. Thus I suggest thinking more about the correct approach to this if your files are really big.

    Check this for reading contents of a file: How do I create a Java string from the contents of a file?