java - 在文件中搜索字符串并返回下一行(在 Java 中)

标签 java string file string-comparison

正如我的标题所说。我需要在文件中搜索字符串。找到后,我需要下一行。 这是一个像这样的文件:

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/

相关文章:

windows - 优化 - 使用 Windows API 从磁盘读取文件

java - 应用程序崩溃: Attempt to invoke virtual method on a null object reference

java - 在 void 函数中使用 Return 的底层分析

java - 单击 JButton 时打印特定值

java - 我不明白为什么我的 if 语句有效

c++ - 将字符串文字传递给函数并分配给成员变量

java - 是否有一个固定大小的队列可以删除过多的元素?

python - 最长重复子串

Java Web 启动 : How to write files to windows UNC Path?

c - 如何使用 scanf 读取完整文件可能类似于 %[^\EOF] 而无需在单个语句中循环