Java 读取文本文件并跳过空行直到达到 EOF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22889561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading text file and skipping blank lines until EOF is reached
提问by Ofek
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:
我正在尝试读取充满文本的 csv 文件;但是,如果中间某处有一个空行,整个事情就会中断,我得到一个:
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
}
}
}
采纳答案by lreeder
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
}
}