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

ars*_*nal 1 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?
     }
Run Code Online (Sandbox Code Playgroud)

任何建议将不胜感激.

Boh*_*ian 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;
}
Run Code Online (Sandbox Code Playgroud)