How do I get the previous line by reading the file line by line

advertisements

I am reading a file line by line using Scanner. So my question is how can I also store the previous line side by side as we keep on moving to next line.

    while (scanner.hasNextLine()) {
    line = scanner.nextLine();//this will get the current line
    if (line.contains("path=/select")){
    // So whenever I enter in this if loop or this loop is true, I also want to
    have the  previous line in any String variable. How can we achieve this?
     }

Any suggestions will be appreciated.


String previousLine = null;
while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    if (line.contains("path=/select")) {
        // use previousLine here (null for the first iteration or course)
    }
    previousLine = line;
}