Skip to content
Advertisement

Ignoring blank lines in CSV file in Java

I am trying to iterate through a CSV file in Java. It iterates through the entire file, but will get to the end of the file and try to read the next blank line and throw an error. My code is below.

JavaScript

Like I typed, this works fine until it gets to the end of the file. When it gets to the end of the file, I get the error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at com.ucg.layout.ShelfTableUpdates.main(ShelfTableUpdates.java:23). I’ve stepped through the code by debugging it in Spring Tool Suite. The error comes up whenever I try to reference data[0] or data[6]; likely because there is nothing in that line. Which leads me back to my original question of why it is even trying to read the line in the first place.

It was my understanding that while ((line = br.readLine()) != null) would detect the end of the file, but it doesn’t seem to be. I’ve tried re-opening the file and deleting all of the blank rows, but that did not work.

Any idea how I can detect the end of the file so I don’t get an error in this code?

ANSWER: Credit goes to user @quemeraisc. I also was able to replace the commas with blanks, and if the line then equals null or “”, then you know that it is the end of the file; in my case, there are no blank rows before the end of the file. This still does not solve the problem of detecting the end of the file in that if I did have blank rows in between my data that were not the EOF then this would detect those.

Solution 1:

JavaScript

Solution 1:

JavaScript

Advertisement

Answer

public String readLine() will read a line from your file, even empty lines. Thus, when you split your line, as in String[] data = line.split(","); you get an array of size 1. Why not try :

JavaScript

which will make sure there are at least 7 elements in your array before proceeding.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement