You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java实现txt文件顺序搜索时存在匹配项仍提示未找到问题排查

问题原因

代码的bug属于变量名笔误,出在sequentialSearch方法的匹配逻辑中:
原本要将用户输入的检索词和文件逐行读取到的内容fileItem做忽略大小写匹配,实际代码错误地写成了和**文件名fileName**做比对,自然永远匹配不到文件里的条目,只会返回false。

修复方案

将sequentialSearch方法里的if判断条件

if(searchItem.equalsIgnoreCase(fileName)) 

修改为:

// 额外给读取到的文件内容也做trim,避免文件行首尾有空格导致匹配失败
if(searchItem.equalsIgnoreCase(fileItem.trim())) 
可选优化项
  • 当前打印搜索状态的代码输出会缺少空格,原语句System.out.println("Searching file" + fileName + "...");输出效果为Searching filetest.txt...,可以修改为System.out.println("Searching file " + fileName + "...");提升可读性
  • 读取文件的Scanner使用完毕后建议关闭,或者使用Java 7+支持的try-with-resources语法自动释放资源,避免资源泄漏,修改后的sequentialSearch方法示例如下:
public static boolean sequentialSearch (String fileName, String searchItem) {           
    boolean result = false;
    // try-with-resources会在代码块执行完毕后自动关闭Scanner资源
    try (Scanner f = new Scanner(new File(fileName))) {
        String fileItem;
        while(f.hasNextLine()) {
            fileItem = f.nextLine();
            if(searchItem.equalsIgnoreCase(fileItem.trim())) {
                result = true;
                break;
            }
        }
    } catch(FileNotFoundException e) {
        System.out.println(e.toString());
        System.exit(0);
    }
    return result;
}

内容的提问来源于stack exchange,提问作者Styles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:09:03