Creating a Java program to search for a file for a specific word

I am just learning this language and wondering what a more experienced Java programmer will do in the following situation.

I would like to create a java program that will search for the specified file for all instances for a specific word.

How would you do this, does this Java API have a class that provides file scanning capabilities, or do I need to write my own class for this?

Thanks for any input,
House.

+3
source share
3 answers

The java API offers a class java.util.Scannerthat will allow you to scan through the input file.

, , . ? ? , lucene.

+6

,

String text = IOUtils.toString(new FileReader(filename));
boolean foundWord = text.matches("\\b" + word+ "\\b");

, split() .

+3

, Scanner.

data.txt :

import java.io.*;
import java.util.Scanner;
import java.util.regex.MatchResult;

public class Test {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner s = new Scanner(new File("data.txt"));
        while (null != s.findWithinHorizon("(?i)\\bjava\\b", 0)) {
            MatchResult mr = s.match();
            System.out.printf("Word found: %s at index %d to %d.%n", mr.group(),
                    mr.start(), mr.end());
        }
        s.close();
    }
}

:

Word found: Java at index 74 to 78.
Word found: java at index 153 to 157.
Word found: Java at index 279 to 283.

, , (?i)\bjava\b, :

  • (?i)
  • \b
  • java -
  • \b .

If the search request comes from a user or if for any other reason, may contain special characters, I suggest you use \Qand \Earound the line, because he quotes all characters between them (and if you are really picky, make sure that the entrance is free \E).

+3
source

Source: https://habr.com/ru/post/1778167/


All Articles