3

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

1 回答 1

12

正是这部分导致了问题:

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
    }           
}
于 2014-04-06T03:17:17.923 回答