这是我当前的代码:
File data = new File("text.txt");
try {
Scanner load = new Scanner(data);
while (load.hasNextLine()) {
String line = load.nextLine();
if (line == "end") break;
System.out.println(line);
}
load.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
这是text.txt
中包含的文本:
line1 line2 line3 end line5 line6
我希望它只输出在行end
之前的行,但会打印每行。如何解决此问题?
==
运算符。像line.equals("end")
以下代码可以正常工作:
File data = new File("text.txt");
try {
Scanner load = new Scanner(data);
while (load.hasNextLine()) {
String line = load.nextLine();
if (line.equals("end")) break;
System.out.println(line);
}
load.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
}