Reading text file and skipping blank lines until EOF is reached

Ofek picture Ofek · Apr 6, 2014 · Viewed 27.4k times · Source

I am trying to read csv file full of text; however if there is a blank line in the middle somewhere, the whole thing breaks and I get a:

java.lang.RuntimeException: java.lang.StringIndexOutOfBoundsException

How would I go about removing/ignoring blank lines as long as it's not the end of the file?

        file = new FileReader(fileName);
        @SuppressWarnings("resource")
        BufferedReader reader = new BufferedReader(file);
        while ((line = reader.readLine()) != null) {
                     //do lots of stuff to sort the data into lists etc
        }
    } catch (Exception e) {
        System.out.println("INPUT DATA WAS NOT FOUND, PLEASE PLACE FILE HERE: " + System.getProperty("user.dir"));
        throw new RuntimeException(e);
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
                // Ignore issues during closing
            }
        }
    }

Answer

lreeder picture lreeder · Apr 6, 2014

It's this part that's causing problems:

while ((line = reader.readLine()) != null) {

      //do lots of stuff to sort the data into lists etc
      // **** Something assumes line is not empty *******
    }

To ignore blank lines, add this check to make sure the line has something:

while ((line = reader.readLine()) != null) {
    if(line.length() > 0) {
      //do lots of stuff to sort the data into lists etc
    }           
}