Meaningless Drivel is fun!
The moose likes I/O and Streams and the fly likes .csv-file import and export problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark ".csv-file import and export problem" Watch ".csv-file import and export problem" New topic

.csv-file import and export problem

Vincent Hendriks

Joined: Oct 19, 2010
Posts: 16
Hi Guys,

I have a problem. Hope you can help me.
I am building an faq program with an arraylist of objects (each with variables Question, Answer and Type).
I'm exporting this arraylist to a .csv-file, wich goes OK.

This is the problem:

Since Questions and Answers can contain semicolons (separators for the .csv), I have had to place the Questions and Answers in quotes (' " ' in lines 34 and 35) to make sure everything is displayed correct in Excel.
These quotes don't appear in the excel-sheet , but when I import the same file again, two problems arise:

1 the quotes are made part of the Questions/Answers and
2 when I have semicolons in the Questions/Answers, they screw up the split-method and for instance my Question is half in the question field/half in the answer field and my answer is nowhere to be seen

Is there a way to solve these problems inside my import-/exportcode (I don't want to mess with the windows-separator value in controlpanel)?

These are my import and export methods. Any help/tips are appreciated!

Jason Cone

Joined: Jul 21, 2004
Posts: 25
You need to ignore semicolons inside quotation marks. Your choices are to come up with a regular expression that will match only semicolons outside of quotation marks and then pass that regex to your split method, or you can get rid of the split method entirely and parse each line, yourself, using indexOf() and substring() inside of a while loop.

Something like the following would work for the "do it yourself" approach (although this one is looking for commas rather than semicolons):

Lester Burnham

Joined: Oct 14, 2008
Posts: 1337
CSV is not as trivial to parse as it first looks. I generally advise to use a ready-made library; several are listed in the page.
Vincent Hendriks

Joined: Oct 19, 2010
Posts: 16
Thanks both Jason and Lester for your reply.

Jason's suggestion is a bit out of my league at the moment (much stuff unknown to me). I'll have a look at it though: I'l consider it an opportunity to expand my API knowledge
I'll also start on Lester's suggestion. I'm looking for a format to import and export, but not necessarily .csv. Maybe there are better options :-)

So, it's back to the drawing board ( head hurts enough for today )

It is sorta covered in the JavaRanch Style Guide.
subject: .csv-file import and export problem
It's not a secret anymore!