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

如何在读取文本文件时遇到第二个逗号后停止打印行内容

解决方案

有两种简单的方法可以实现你要的效果:提取每行第二个逗号之前的内容。

方法1:通过索引截取字符串

直接定位第二个逗号的位置,然后截取该位置之前的内容,这种方法效率高且逻辑直观:

public static void fileReader() throws FileNotFoundException {
    File file = new File("/Users/14077/Downloads/inventory.txt");
    Scanner scan = new Scanner(file);
    String test = "4452";
    
    while (scan.hasNext()) {
        String line = scan.nextLine();
        // 先判断当前行是否匹配目标ID(避免ID是其他字符串的前缀,比如4452和44521)
        if (line.startsWith(test + ",")) {
            int firstComma = line.indexOf(',');
            if (firstComma != -1) {
                // 从第一个逗号的下一位开始找第二个逗号
                int secondComma = line.indexOf(',', firstComma + 1);
                if (secondComma != -1) {
                    // 截取到第二个逗号之前的内容
                    String desiredContent = line.substring(0, secondComma);
                    System.out.println(desiredContent);
                } else {
                    // 如果行中只有一个逗号,直接输出整行
                    System.out.println(line);
                }
            } else {
                // 行中没有逗号,直接输出整行
                System.out.println(line);
            }
        }
    }
    // 记得关闭资源
    scan.close();
}

方法2:改进split的用法

你之前尝试了split但用错了方式,其实可以设置split的限制参数为3,这样会把字符串分割成最多3部分(前两个逗号分割的内容,以及剩下的所有内容),然后取前两部分拼接即可:

public static void fileReader() throws FileNotFoundException {
    File file = new File("/Users/14077/Downloads/inventory.txt");
    Scanner scan = new Scanner(file);
    String test = "4452";
    
    while (scan.hasNext()) {
        String line = scan.nextLine();
        String[] parts = line.split(",", 3);
        if (parts[0].equals(test)) {
            if (parts.length >= 2) {
                // 拼接前两部分,保留原有的逗号分隔
                String desiredContent = parts[0] + "," + parts[1];
                System.out.println(desiredContent);
            } else {
                System.out.println(line);
            }
        }
    }
    scan.close();
}

为什么你之前的方法无效?

  • 你用split(",",5)后遍历所有元素打印,相当于把分割后的每一部分单独输出,自然会显示整行拆分后的所有内容;
  • 只打印itemID[0]当然只会得到第一个逗号之前的内容,因为split的第一个元素就是逗号前的部分。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 08:01:01