2011-12-07 133 views
1

我正在使用掃描程序逐行讀取文件。所以我的問題是,我們如何能夠將前一行並排存儲,因爲我們繼續前進到下一行。如何通過逐行讀取文件來獲取上一行

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

任何建議,將不勝感激。

回答

4
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; 
} 
+0

+1打我到標記。 – AusCBloke

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

我假設,如果沒有前行,那麼你就不會想要進入if塊。

+0

你對'line!= null'的測試是毫無意義的。看看你是否能弄清楚爲什麼 – Bohemian

+0

@波希米亞:應該是'prevLine'以符合代碼下面的文本...:/ – AusCBloke