使用 BufferedReader 从特定点开始读取到 EOF

Start Reading from a specific point to EOF using BufferedReader

我有一个 class 逐行读取日志文件,我想从文件中的特定点开始直到文件末尾。例如,从时间戳 '2018-11-23 09:00' 开始读取到文件末尾。我检查了与读取文件相关的 BufferedReader 问题,但 none 的答案有所帮助。

BufferedReader reader = new BufferedReader(new FileReader(path));
while ((line = reader.readLine()) != null) {
    if(!line.isEmpty()){//I would like to start reading from a specific timestamp to the end of the file
        if(line.toLowerCase().contains(keyword)){
            if(line.length() > 16) {
                if (line.substring(0, 1).matches("\d")){
                    dateTimeSet.add(line.substring(0, 16));//Adds timestamp to my list
                    errorSet.add(line);
                }
            }
        }
    }
}

由于您要查找文件中出现的特殊字符串,因此您需要检查每一行直到找到它。

添加一个局部变量来跟踪您是应该处理还是跳过该行

boolean isReading = false;

然后代替您的isEmpty检查

 if (!isReading) {
     isReading = line.startsWith(timestamp);
 }

 if (!isReading) {
     continue;
 }

 //otherwise process line

如果您不能始终匹配时间戳,您最好使用 matches() 和正则表达式而不是 startsWith()