A D
A D

Reputation: 809

Knowing delimiters for CSV file

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

Upvotes: 0

Views: 10441

Answers (4)

Raptor
Raptor

Reputation: 54212

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(",");

Upvotes: 1

corsiKa
corsiKa

Reputation: 82579

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.

Upvotes: 3

Brad
Brad

Reputation: 603

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]*");

Upvotes: 1

Omar Estrella
Omar Estrella

Reputation: 638

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

s.useDelimiter(",");

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

Upvotes: 1

Related Questions