2011-12-07 49 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