gpt4 book ai didi

java - 读取文本文件并跳过空行直到达到 EOF

转载 作者:行者123 更新时间:2023-12-03 23:13:38 29 4
gpt4 key购买 nike

我正在尝试读取充满文本的 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
}
}
}

最佳答案

正是这部分导致了问题:

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

关于java - 读取文本文件并跳过空行直到达到 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22889561/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com