
本文介绍如何使用 string.indexof() 和 substring() 高效截取每行文本中第二个逗号及其之前的所有内容,适用于解析csv-like格式的库存数据等场景。
在处理结构化文本(如简易CSV格式)时,有时需按特定分隔符(如英文逗号 ,)进行非完整分割——例如仅保留前两个字段(即截止到第二个逗号为止),而非将整行拆成全部字段。此时,盲目使用 split()(尤其带 limit 参数)容易导致逻辑偏差:split(",", 5) 会将字符串最多切为5段,但无法直接获取“第二个逗号位置”,而 itemID[0] 只取首字段,itemID[1] 又不包含第一个逗号,难以拼出符合要求的 14, "Stanley #2 Philips Screwdriver" 这类带分隔符的原始片段。
正确解法是定位第二个逗号的索引,再截取子串。Java 的 String.indexOf(String str, int fromIndex) 支持从指定位置开始搜索,因此可分两步:
- 第一次调用 line.indexOf(",") 获取首个逗号位置;
- 第二次调用 line.indexOf(",", firstIndex + 1) 从首个逗号后一位开始搜索,得到第二个逗号位置;
- 使用 substring(0, secondIndex + 1) 截取包含该逗号的前缀(注意 +1 是为了包含逗号本身)。
以下是修正后的完整示例代码(已整合文件读取与条件匹配逻辑):
public static void fileReader() throws FileNotFoundException {
File file = new File("/Users/14077/Downloads/inventory.txt");
Scanner scan = new Scanner(file);
String targetId = "14"; // 注意:原问题中 test = "4452",此处以示例数据 "14" 为准
while (scan.hasNextLine()) {
String line = scan.nextLine().trim();
if (line.isEmpty()) continue;
// 查找第二个逗号的位置
int firstComma = line.indexOf(',');
if (firstComma == -1) continue; // 无逗号,跳过
int secondComma = line.indexOf(',', firstComma + 1);
if (secondComma == -1) continue; // 少于两个逗号,跳过
// 截取到第二个逗号(含)
String truncated = line.substring(0, secondComma + 1);
// 按需求匹配首字段(如 item ID)
String firstField = line.substring(0, firstComma).trim();
if (firstField.equals(targetId)) {
System.out.println(truncated); // 输出:14, "Stanley #2 Philips Screwdriver"
}
}
scan.close(); // 建议显式关闭资源
}✅ 关键注意事项:
立即学习“Java免费学习笔记(深入)”;
- 必须检查 indexOf() 返回值是否为 -1,避免 substring() 抛出 StringIndexOutOfBoundsException;
- split() 适合均匀分割,而本需求本质是基于分隔符位置的字符串切片,indexOf + substring 更精准、高效、无正则开销;
- 若输入含转义逗号(如 CSV 中引号内 ,),此方法不适用——需引入专业 CSV 解析器(如 OpenCSV);
- 使用 hasNextLine() 替代 hasNext() 更安全,避免因换行符导致异常;
- 记得关闭 Scanner(或使用 try-with-resources)防止资源泄漏。
该方案简洁、可读性强,且时间复杂度为 O(n),适用于千行级日志或配置文件的轻量解析任务。










