简体   繁体   English

如何不逐行查找 BufferedReader class object 是否包含特定单词?

[英]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.所以这些文件的名称: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.为了获取为其生成日志的文件的名称,我必须逐行遍历 BufferedReader br 并检查所有 4 个名称,如果该名称出现在某个需要大量时间的行中。

Is there any way to iterate through these 4 names and check in Bufferedreader if the specific word is contained by the BufferedReader object.如果 BufferedReader object 包含特定单词,是否有任何方法可以遍历这 4 个名称并检查 Bufferedreader。 Something like String.contains("s") for BufferedReader. BufferedReader 的类似 String.contains("s") 的东西。 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.可以为 BufferedReader 指定缓冲区大小,但您必须实际读取行。 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.可以读取一些字节缓冲区并将其转换为要搜索的字符串。问题是对于 UTF-8 缓冲区可能以拆分的多字节序列结束。 Not difficult to take care of, but why not use simple code, not depending on a buffer size.不难处理,但为什么不使用简单的代码,而不取决于缓冲区大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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