Java Scanner读取文件时分隔符失效,数组列表内容读取异常
解决Java Scanner读取文件时逗号分隔符失效的问题
嘿,我来帮你排查这个问题!你的代码里有两个关键问题导致输出不符合预期,咱们一步步理清楚:
问题出在哪?
先看你当前的代码:
while(instructorInput.hasNextLine()) { Scanner lineSeperator = new Scanner(instructorInput.next()); lineSeperator.useDelimiter(","); lines.add(lineSeperator.next()); } System.out.print(lines.get(0) + " "); System.out.println(lines.get(1));
- 外层Scanner用错了方法:
instructorInput.next()是按空白字符(空格、换行等)分割输入的,所以你文件里的5005,Black Lizards,US...这一行,会被拆成5005,Black和Lizards,US...两个片段。这就是为什么你最后拿到的是5005和Lizards——两次循环分别处理了这两个被拆分的部分。 - 内层Scanner只取了第一个元素:就算你拿到了整行,现在的代码也只会把每行第一个逗号前的内容加入列表,而你需要的是前两个逗号分隔的内容(
5005和Black Lizards)。
修复方案
咱们调整两处代码,就能得到预期结果:
方案一:正确读取整行并拆分
// 外层Scanner读取完整的一行 while(instructorInput.hasNextLine()) { String line = instructorInput.nextLine(); // 读取整行内容 Scanner lineSeperator = new Scanner(line); lineSeperator.useDelimiter(","); // 读取第一个分隔元素(5005) if(lineSeperator.hasNext()) { lines.add(lineSeperator.next().trim()); } // 读取第二个分隔元素(Black Lizards) if(lineSeperator.hasNext()) { lines.add(lineSeperator.next().trim()); } lineSeperator.close(); // 关闭内层Scanner释放资源 } // 输出预期结果 System.out.print(lines.get(0) + " "); System.out.println(lines.get(1));
方案二:用String.split()更简洁
如果只是简单按逗号分割字符串,用String.split()会更直观,不需要嵌套Scanner:
while(instructorInput.hasNextLine()) { String line = instructorInput.nextLine(); // 按逗号分割字符串,trim()去掉元素前后可能的空格 String[] parts = line.split(","); if(parts.length >= 2) { lines.add(parts[0].trim()); lines.add(parts[1].trim()); } } System.out.print(lines.get(0) + " "); System.out.println(lines.get(1));
这两种方案都能让你得到预期的5005 Black Lizards输出。另外,记得用完外层的instructorInput后调用close(),避免资源泄漏哦~
内容的提问来源于stack exchange,提问作者hockey34
相关产品推荐
相关产品推荐

