1

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?

1
  • 3
    I would recommend OpenCSV. Commented Jan 4, 2014 at 16:35

2 Answers 2

1

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.

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

Comments

1

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.

2 Comments

So If I don't pass '"', it will have problems with entries involving " right?
" characters in fields require a double "". See the example here: en.wikipedia.org/wiki/Comma-separated_values#Example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.