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 に答える