0

This may be a simple question but I have not been able to find a satisfactory answer. I am writing a class in Java that needs to take in a .csv file filled with doubles in three columns. Obviously a .csv file uses commas as the delimiters, but when I try setting them with my scanner, the scanner finds nothing. Any advice?

Scanner s = null; try { s = new Scanner(source); //s.useDelimiter("[\\s,\r\n]+"); //This one works if I am using a .txt file //s.useDelimiter(", \n"); // This is what I thought would work for a .csv file ... } catch (FileNotFoundException e) { System.err.format("FileNotFoundException: %s%s", e); } catch (IOException e) { System.err.format("IOException: %s%n", e); } 

A sample input would be:

12.3 11.2 27.0

0.5 97.1 18.3

etc.

Thank you for your time!

EDIT: fixed! Found the correct delimiters and realized I was using hasNextInt() instead of hasNextDouble(). /facepalm

4
  • Can you provide a sample line or two of your .csv file? Commented Apr 18, 2011 at 3:43
  • Sure. I will add it to my question Commented Apr 18, 2011 at 3:44
  • You might want to take a look at stackoverflow.com/questions/3908012/parsing-csv-in-java Commented Apr 18, 2011 at 3:44
  • I don't see any commas in your example inputs. Commented Mar 30, 2017 at 20:31

4 Answers 4

3

Consider the following:

first,second,"the third",fourth,"the,fifth" 

Should only be five - the last comma is in a quote block, which should not get split.

Don't reinvent the wheel. There are open source libraries to handle this behavior.

A quick google search yielded http://opencsv.sourceforge.net/ and I'm sure there's others.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I thought it would be simpler to code it myself because the input will always be exactly the same
Apache Commons CSV is a good library that parses and generates a variety of CSV formats as well as Tab-delimited files.
1

If you are trying to read each individual item, try:

s.useDelimiter(","); 

Then s.next() would return an item from the CSV.

Comments

1

Why have you got a \n in your CSV delimiter? Java doesn't have a difference between CSV and TXT files, if they have the same content.

I would think you would want

s.useDelimiter(","); 

or

s.useDelimiter("[\\s]+,[\\s\r\n]*"); 

1 Comment

I must say I prefer glowcoder's response to my own. I used to have a homebrew CSV parser in our app and it caused me many headaches.
1

There are several methods to workaround:

Method 1: use conditional statements ( if-else / switch ) in file extension.

if(ext == 'csv') { s.useDelimiter(", \n"); } else if(ext == 'txt') { s.useDelimiter("[\\s,\r\n]+"); } 

Method 2: as other answers suggested, use this:

s.useDelimiter(","); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.