2

I have a csv file that goes like this

Mike,Smith
Scuba,Steve
John,Doe

And java code that goes like this:

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

1 Answer 1

5

This is because Smith\nScuba becomes one token. (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:

Files.lines(Paths.get("input.txt"))
     .forEach(line -> {
         Scanner s = new Scanner(line);
         s.useDelimiter(",");
         System.out.println(s.next() + " " + s.next());
     });
Sign up to request clarification or add additional context in comments.

2 Comments

It seems easier just to use String.split at that point. Spawning loads of Scanners isn't fast...
If split does the job, then sure. Since the OP was using Scanner, I thought that maybe his actual code was a bit more complicated. Regardless, the best approach is probably to use a CSV library, so that stuff like a,"b,c",d is handled correctly as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.