我正在使用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?
}
任何建议都将受到赞赏。
答案 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
块。