arsenal
arsenal

Reputation: 24144

how can I get the previous line by reading file line by line

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.

Upvotes: 1

Views: 13530

Answers (2)

AusCBloke
AusCBloke

Reputation: 18492

prevLine = null; // null indicates no previous lines

while (scanner.hasNextLine()) {
    line = scanner.nextLine(); //this will get the current line
    if (line.contains("path=/select") && prevLine != null){
        // ...
    }
    prevLine = line;
}

I'm assuming that if there's no previous line, then you wouldn't want to enter the if block.

Upvotes: 1

Bohemian
Bohemian

Reputation: 424983

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

Upvotes: 6

Related Questions