Sarp Kaya
Sarp Kaya

Reputation: 3784

Making a simple CSV file in Java

I would like to store some String in a file and then read it back again. The problem is Strings could be anything for instance it could even be something like "Entry1","Entry2" for one field. So if I simply check commas and split Strings accordingly to that it will definitely fail.

Is there any built-in Java class that handles situations like that? If not how can I make a simple CSV parser in Java?

Upvotes: 1

Views: 218

Answers (2)

Durandal
Durandal

Reputation: 5663

I would recommend openCSV: http://opencsv.sourceforge.net/

I have used it for numerous Java projects requiring CSV support, both reading and writing. A simple example of how it writes a CSV from the docs:

CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), ',');
 // feed in your array (or convert your data to an array)
 String[] entries = "first,second,third".split(",");
 writer.writeNext(entries);
writer.close();

Assuming you can make a String[] out of your data it's that simple.

To deal with comma's in your entries you'd need to quote the entire entry:

`Make,Take,Break", "Top,Right,Left,Bottom",

With OpenCSV you can provide a quote character,you just pass it in the constructor:

CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), ',', '"');

That should take care of the needs you listed.

Upvotes: 1

sTg
sTg

Reputation: 4424

You might want to have a look at thisspecification for CSV. Bear in mind that there is no official recognized specification. You can probably try this parser too else There is Apache Common library for CSV too that can help.

If you do not know about delimiter it will not be possible to do this so you have to find out somehow. If the delimiter can vary your only hope is to be able to deduce if from the formatting of the known data. When Excel imports CSV files it lets the user choose the delimiter and this is a solution you could use as well.

Upvotes: 1

Related Questions