读取文本文件并跳过空行,直到达到EOF [英] Reading text file and skipping blank lines until EOF is reached
本文介绍了读取文本文件并跳过空行,直到达到EOF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试读取包含文本的csv文件;但是,如果中间某行有空白行,则整个过程都会中断,并且我会得到:
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
}
}
}
推荐答案
这是引起问题的部分:
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
}
}
这篇关于读取文本文件并跳过空行,直到达到EOF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文