Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading text file and skipping blank lines until EOF is reached

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
            }
        }
    }
like image 641
Ofek Avatar asked Dec 02 '25 01:12

Ofek


1 Answers

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
    }           
}
like image 181
lreeder Avatar answered Dec 03 '25 14:12

lreeder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!