正如我的标题所说。我需要在文件中搜索字符串。找到后,我需要下一行。 这是一个像这样的文件:
hello
world
当找到“hello”时,需要返回“world”。
File file = new File("testfile");
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (scanner != null) {
String line;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (line == "hello") {
line = scanner.nextLine();
System.out.println(line);
}
}
}
它通读文件但没有找到单词“hello”。
最佳答案
if (line == "hello") {
应该是
if ("hello".equals(line)) {
您必须使用 equals() 方法来检查两个字符串对象是否相等。 ==
运算符在字符串(和所有对象)的情况下仅检查两个引用变量是否引用同一对象。
关于java - 在文件中搜索字符串并返回下一行(在 Java 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15044985/