如何通过逐行读取文件来获取上一行

时间:2011-12-07 06:01:07

标签: java java.util.scanner

我正在使用Scanner逐行读取文件。所以我的问题是,当我们继续前进到下一行时,我如何能够并排存储前一行。

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

任何建议都将受到赞赏。

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分: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块。