我正在尝试读取充满文本的csv文件;但是如果某个地方的中间有一个空行,整个事情就会中断,我得到了一个:
java.lang.RuntimeException: java.lang.StringIndexOutOfBoundsException
如果不是文件的末尾,我将如何删除/忽略空行?
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
}
}
}
答案 0 :(得分:9)
这部分导致了问题:
while ((line = reader.readLine()) != null) {
//do lots of stuff to sort the data into lists etc
// **** Something assumes line is not empty *******
}
要忽略空白行,请添加此检查以确保该行包含以下内容:
while ((line = reader.readLine()) != null) {
if(line.length() > 0) {
//do lots of stuff to sort the data into lists etc
}
}