Reading File Go Back to Previous Line Java
I am reading a file line past line using Scanner. And then my question is how tin can I as well store the previous line next as we keep on moving to adjacent line.
while (scanner.hasNextLine()) { line = scanner.nextLine();//this volition go the current line if (line.contains("path=/select")){ // So whenever I enter in this if loop or this loop is truthful, I also desire to have the previous line in whatever String variable. How tin we achieve this? }
Whatsoever suggestions will be appreciated.
asked Dec 7, 2011 at half-dozen:01
arsenalarmory
21.7k 82 gilded badges 221 argent badges 323 statuary badges
2 Answers 2
Cord previousLine = zippo; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("path=/select")) { // utilise previousLine here (nada for the first iteration or grade) } previousLine = line; }
answered Dec 7, 2011 at 6:03
Bohemian♦ Bohemian
384k 87 gold badges 543 silvery badges 685 bronze badges
0
prevLine = null; // null indicates no previous lines while (scanner.hasNextLine()) { line = scanner.nextLine(); //this volition get the current line if (line.contains("path=/select") && prevLine != null){ // ... } prevLine = line; }
I'm bold that if there's no previous line, and so you lot wouldn't want to enter the if
block.
answered Dec 7, 2011 at 6:04
AusCBlokeAusCBloke
17.2k 6 gold badges 39 silver badges 44 bronze badges
two
Not the respond you're looking for? Scan other questions tagged java java.util.scanner or inquire your ain question.
Source: https://stackoverflow.com/questions/8411057/how-can-i-get-the-previous-line-by-reading-file-line-by-line
Your examination for
line != nix
is completely pointless. Run across if yous can effigy out whyDec seven, 2011 at 6:07
@Bohemian: woops that was supposed to exist
prevLine
to correspond with the text below the code... :/Dec 7, 2011 at 6:10