我正在从 java 类中的制表符分隔文件读取输入。文件正确打开,并且文件中的信息似乎也被正确读取。文件中的每一行都会按预期打印到屏幕上,但在文件末尾,它似乎尝试再打印一行,我得到一个 ArrayIndexOutOfBoundsException: 1。
值得注意的是,如果我取消注释输出 sCurrentline 值的行并注释掉分割数组的输出,我不会收到错误。
代码:
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();
}
}
最佳答案
最后一行的元素数量与其他行不同。分割最后一行后,您尝试访问数组中不存在的字段。异常 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();
}
}
关于java - Java中的文件IO异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24797331/