/ / Odczytywanie pliku tekstowego i pomijanie pustych wierszy aż do osiągnięcia EOF - java, bufferedreader, runtimeexception, blank-line

Czytanie pliku tekstowego i pomijanie pustych linii do momentu osiągnięcia EOF - java, bufferedreader, runtimeexception, blank-line

Próbuję odczytać plik csv pełen tekstu; jednak jeśli w środku jest pusta linia, wszystko się psuje i dostaję:

java.lang.RuntimeException: java.lang.StringIndexOutOfBoundsException

Jak mam usunąć / ignorować puste linie, o ile nie jest to koniec pliku?

        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
}
}
}

Odpowiedzi:

8 dla odpowiedzi № 1

To ta część powoduje problemy:

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

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

Aby zignorować puste linie, dodaj tę opcję, aby upewnić się, że linia ma coś:

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