Java中的文件IO异常

时间:2014-07-17 07:26:32

标签: java io

我正在读取java类中制表符分隔文件的输入。文件正常打开,文件中的信息似乎也正确读取。文件中的每一行都按预期结束打印到屏幕,但是在文件末尾,它似乎尝试再打印一行,我得到一个ArrayIndexOutOfBoundsException:1。

值得注意的是,如果我取消注释输出sCurrentline值的行并注释掉split数组的输出,我就不会收到错误。

代码:

BufferedReader br = null;

try {
        String sCurrentLine;

        br = new BufferedReader(new FileReader(fname));

        while ((sCurrentLine = br.readLine()) != null){

            String[] values = sCurrentLine.split("\\t", -1); // don't truncate empty fields

            System.out.println("Col1: " + values[0] + " Col2: " + values[1] + " Col3: " 
            + values[2] + " Col4: " + values[3] + " Col5: " + values[4] );

            //System.out.println(sCurrentLine);

        }
} catch (IOException e) {
    System.out.println("IOException");
    e.printStackTrace();
} finally {
    try {
        if(br != null){
            br.close();
        }
    } catch (IOException ex) {
        System.out.println("ErrorClosingFile");
        ex.printStackTrace();
    }
}

3 个答案:

答案 0 :(得分:2)

最后一行与其他行的元素数量不同。拆分最后一行后,您尝试访问不存在的数组字段。这由例外http://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html表示。在访问阵列的字段之前,您必须检查其中是否有预期的项目数量。像这样:

BufferedReader br = null;

try {
    String sCurrentLine;
    br = new BufferedReader(new FileReader(fname));

    while ((sCurrentLine = br.readLine()) != null){
        String[] values = sCurrentLine.split("\\t", -1); // don't truncate empty fields

        if (5 == values.length) {
            System.out.println("Col1: " + values[0] + " Col2: " + values[1] + " Col3: " 
            + values[2] + " Col4: " + values[3] + " Col5: " + values[4] );
        }

        // System.out.println(sCurrentLine);
    }
} catch (IOException e) {
    System.out.println("IOException");
    e.printStackTrace();
} finally {
    try {
        if(br != null){
            br.close();
        }
    } catch (IOException ex) {
        System.out.println("ErrorClosingFile");
        ex.printStackTrace();
    }
}

答案 1 :(得分:1)

代码似乎没问题......你最后有一个空的换行符吗?

while ((sCurrentLine = br.readLine()) != null){
    if (sCurrentLine.isEmpty() || sCurrentLine.startsWith(";")) // skip empty and comment lines
        continue;

    String[] values = sCurrentLine.split("\\t"); // are you sure the -1 is required?
...
}

答案 2 :(得分:0)

试试这个

    String[] values = "".split("\\t", -1); // don't truncate empty fields
    int index=1;
    StringBuffer sb = new StringBuffer();
    for (String value : values) {
         sb.append("Col"+index+":").append(value).append(" ");
        index++;
    }
    System.out.println(sb.toString());

显然您正在读取不存在的数组位置