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("开发者_C百科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:
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.
If you are trying to read each individual item, try:
s.useDelimiter(",");
Then s.next()
would return an item from the CSV.
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]*");
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(",");
精彩评论