简体   繁体   中英

How to find if the BufferedReader class object contains a specific word without going through line by line?

I have some log files inside which the name of the file for which the logs are generated is written at an unknown line.

There are fixed files for which logs are generated. So the name of the files of these: Image_1, Image_5, Image_10,Image_25.

For getting the name of the file for which the logs are generated, I have to iterate through BufferedReader br line by line and check for all 4 names,if this name is present in some line which takes a lot of time.

Is there any way to iterate through these 4 names and check in Bufferedreader if the specific word is contained by the BufferedReader object. Something like String.contains("s") for BufferedReader. Is it possible to it this way or some better alternative?

A BufferedReader can be given a buffer size, but you have to actually read the lines. The most easiest is to do:

Path path = Paths.get("my.log");
// Assume UTF-8 (is default):
Optional<String> img = Files.lines(path)
    .filter(line -> line.matches("Image_(10?|5|25).*"))
    .findAny();
String file = img.orElse("NOT FOUND");

or better

try (Stream<String> in = Files.lines(path)) {
    Optional<String> img = in
        .filter(line -> line.matches("Image_(10?|5|25).*")
        .findAny();
    String file = img.orElse("NOT FOUND");
}

Clarification:

One could read some byte buffer and convert that to a String to search in. The problem is that for UTF-8 the buffer could end on a split multi-byte sequence. Not difficult to take care of, but why not use simple code, not depending on a buffer size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM