简体   繁体   English

Java扫描器读取CSV文件时读取的内容不存在

[英]Java Scanner reading something that is not there when reading CSV file

I have a csv file that goes like this 我有一个csv文件,像这样

Mike,Smith
Scuba,Steve
John,Doe

And java code that goes like this: 和这样的Java代码:

Scanner file=new Scanner(new File("input.txt"));

file.useDelimiter(",");      
while (file.hasNext()){

   String s1=file.next();
   String s2=file.next();
   System.out.println(s1+" "+s2);

}
file.close();

I get as output: 我得到的输出:

Mike Smith
Scuba
Steve
John Doe

I don't understand what could possibly make this work on the first two names but not the middle one 我不明白在前两个名字上能做得到的是什么,但在中间两个名字上却不行

This is because Smith\\nScuba becomes one token. 这是因为Smith\\nScuba成为一个令牌。 (There's no , separating them.) (没有,将它们分开。)

Using 运用

file.useDelimiter(",|\n");

solves the problem. 解决了问题。


If you happen to be using Java 8, I'd recommend using something like: 如果您碰巧正在使用Java 8,则建议使用类似以下的内容:

Files.lines(Paths.get("input.txt"))
     .forEach(line -> {
         Scanner s = new Scanner(line);
         s.useDelimiter(",");
         System.out.println(s.next() + " " + s.next());
     });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM