Search code examples
javabufferedreader

Start Reading from a specific point to EOF using BufferedReader


I have a class that reads through a log file line by line and I would like to begin from a specific point in the file until the end of the file. For example, start reading from timestamp '2018-11-23 09:00' to the end of the file. I have checked BufferedReader questions relating to reading a file but none of answers helped.

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);
                }
            }
        }
    }
}

Solution

  • Since you are looking for a special string to occur in your file you need to check each line until you find it.

    Add a local variable to keep track of if you should process the line or skip it

    boolean isReading = false;
    

    Then instead of your isEmptycheck do

     if (!isReading) {
         isReading = line.startsWith(timestamp);
     }
    
     if (!isReading) {
         continue;
     }
    
     //otherwise process line
    

    If you can't always match the timestamp you might be better of using matches() and a regular expression instead of startsWith()