Java读取TXT文件时第四行及之后内容无法匹配问题咨询
问题排查与修复方案
根因分析
你的代码逻辑结构完全错位,将「获取用户搜索输入」和「遍历文件行匹配」的逻辑嵌套错误:
- 每次获取用户输入的搜索词后,仅读取1行文件内容就执行
break退出循环,没有遍历文件的全部行做匹配 - 如果你多次输入搜索词,文件的读取指针会逐行后移,最多读3次就到了测试文件的末尾,第4次读取会直接抛出异常被捕获,自然匹配不到第四行的内容
修复方案
调整逻辑顺序:先获取用户要搜索的关键词,再循环遍历文件的所有行做匹配,遍历完全部行仍无匹配再输出未找到。
修改后代码如下:
import java.nio.file.Paths; import java.util.Scanner; public class IsItInTheFile { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Name of the file:"); String fileName = scanner.nextLine(); System.out.println("Search for:"); String searchedFor = scanner.nextLine(); boolean isFound = false; try (Scanner file = new Scanner(Paths.get(fileName))) { // 遍历文件所有行 while (file.hasNextLine()) { String currentLine = file.nextLine(); if (currentLine.contains(searchedFor)) { isFound = true; break; } } // 遍历完成后统一输出结果 System.out.println(isFound ? "Found!" : "Not found."); } catch(Exception e){ System.out.println("Reading the file " + fileName + " failed."); } } }
可选优化说明
如果需要支持用户多次输入搜索词不需要重启程序,可以把「获取搜索词+遍历匹配」的逻辑套在外层循环中,注意每次搜索都要重新初始化文件读取的Scanner,避免指针跑到文件末尾无法二次读取。
内容的提问来源于stack exchange,提问作者Vincenzo
相关产品推荐
相关产品推荐

