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
Consider the following:
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.