Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Splitting a CSV file into an Array

Tags:

java

arrays

csv

I have managed to split a CSV file based on the commas. I did this by placing a dummy String where ever there was a ',' and then splitting based on the dummy String.

However, the CSV file contains things such as:

something, something, something
something, something, something

Therefore, where there is a new line, the last and first values of each line get merged into their own string. How can I solve this? I've tried placing my dummy string where \n is found to split it based on that but to no success.

Help?!

like image 795
mino Avatar asked Feb 02 '12 11:02

mino


2 Answers

I would strongly recommend you not reinventing the wheel :). Go with one of the already available libraries for handling CSV files, eg: OpenCSV

like image 117
Kris Avatar answered Oct 10 '22 19:10

Kris


I don't see why you need a dummy string. Why not split on comma?

BufferedReader in = new BufferedReader(new FileReader("file.csv"));
String line;
while ((line = in.readLine()) != null) {
    String[] fields = line.split(",");
}
like image 5
dogbane Avatar answered Oct 10 '22 20:10

dogbane