3

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
            }
        }
    }
Ofek
  • 325
  • 1
  • 2
  • 13

1 Answers1

13

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
    }           
}
lreeder
  • 12,047
  • 2
  • 56
  • 65
  • 3
    Actually you should do `if(line.trim().length() > 0)` to catch empty lines that may have white space. – Jared Apr 06 '14 at 03:21
  • Cheers, that was a very simple fix! – Ofek Apr 06 '14 at 03:30
  • @Jared Depends on how you define 'blank'. If 'blank' lines have non-terminating whitespace characters, then yes, you'll want to apply `trim()`. If blank lines just have line-termination characters, `reader.readLine()` will return an empty string. – lreeder Apr 06 '14 at 03:32
  • 1
    @lreeder this isn't going to be a problem if you are only reading in computer generated files (which are unlikely to add in unneeded white space). But it _is_ something you should be wary of when reading in manually generated input (where users may accidentally or unknowingly input unneeded white space). – Jared Apr 06 '14 at 03:42