我如何读取多行和结束之前使用扫描器在Java中的某个字符串?



我试图在到达某个字符串"***"之前从文本文件中读取多行,然后我想打印出来。我该怎么做呢?代码:

public void loadRandomClass(String filename) {
try {
Scanner scan = new Scanner(new File(filename));
while((scan.hasNextLine()) && !(scan.nextLine().equals("***"))) {

}
scan.close();
} catch (FileNotFoundException e) {
System.out.println("Something went wrong");
e.printStackTrace();
}

}

我试过一些东西,但它一直跳过每第二行,从第一行开始,它不停止在&;***&;

问题是scan.nextLine()读取该行并将其从缓冲区中删除。试试这个:


while(scan.hasNextLine()) {
String next = scan.nextLine();
if(next.contains("***") break;
System.out.println(next);
}

最新更新