0

I am trying to read a CSV file. However, the CSV file might not be so perfect. This is kind of the requirement.

So this is the CSV file:

Name,Type,Price,DaysExpired
Apple,Fruit,10,3
Banana,Fruit,,
Tomato,,,

As you can see in the CSV file, it is not perfect, it is just a " ,, "

Is it possible to read it? I have this code here:

FileReader fr = new FileReader(propertyFile);
BufferedReader br = new BufferedReader(fr);   
String line;
String lines[];

br.readLine(); //Consume the first line, the labels

line = br.readLine(); //Start reading from the 2nd line

while(line != null)
{
    lines = line.split(",");

    //See the result
    System.out.println(lines[0]);
    System.out.println(lines[1]);
    System.out.println(lines[2]);
    System.out.println(lines[3]);

    line = br.readLine();         

}//End of while 

The output should be:

Apple
Fruit
10
3
Banana
Fruit


Tomato

But instead, I got an error after "Fruit". Is it possible to read it like this?

Please help, Thank you in advance

Jason Christopher
  • 195
  • 2
  • 4
  • 11
  • 1
    Especially the second answer is worth a thousand upvotes. So: dont try to that yourself. Better look for existing solutions that explicitly allow for "not so great" input. – GhostCat Oct 19 '16 at 17:40
  • Try `lines = line.split(",", -1);` so you don't drop trailing separators. The CSV is as perfect you can expect, but if cells are missing, you need to be able to handle that. – Peter Lawrey Oct 19 '16 at 17:40
  • Please also see this question: http://stackoverflow.com/q/14602062/2170192 It explains the peculiarity of `String.split` – Alex Shesterov Oct 19 '16 at 17:42
  • Thank you for the solution guys, appreciate it. – Jason Christopher Oct 19 '16 at 17:52

0 Answers0