Java 拆分从文件读取的字符串时出现ArrayIndexOutOfBoundsException
我一次读一行文件。文件中的每一行都包含两个由空格分隔的数字。为了处理这两个数字,我使用了split函数并创建了一个数组来存储这些值。但是,当我运行程序时,它会给出arrayIndexOutofBoundsException。我以前使用过split函数。我似乎不明白为什么它现在显示它。 我的文本文件中的每一行如下所示: 515 37 代码:Java 拆分从文件读取的字符串时出现ArrayIndexOutOfBoundsException,java,split,indexoutofboundsexception,Java,Split,Indexoutofboundsexception,我一次读一行文件。文件中的每一行都包含两个由空格分隔的数字。为了处理这两个数字,我使用了split函数并创建了一个数组来存储这些值。但是,当我运行程序时,它会给出arrayIndexOutofBoundsException。我以前使用过split函数。我似乎不明白为什么它现在显示它。 我的文本文件中的每一行如下所示: 515 37 代码: for(int i=0;i您的输入文件在文件末尾有空行,因此当“拆分”时 字符串[]大小为1的维度,您将在该行中获得arrayIndexOutofBounds
for(int i=0;i您的输入文件在文件末尾有空行,因此当“拆分”时
字符串[]大小为1的维度,您将在该行中获得arrayIndexOutofBoundsException
String heightS=dimensions[1];首先,修复代码,以便可以真正循环所有文件行。其次,检查数组的长度。第三,打印当前正在读取的行,以便在文件内容出现问题时可以使用
例:
在我看来,您实际上并没有拆分行。也许每次都打印生成的数组,看看发生了什么?只需在使用数组之前检查数组的长度即可。@user3580294发布您的所有文本文件内容是否拆分空行?您应该在使用前验证维度
长度。您的代码看起来像是读取同一个文件5次,我认为您需要的是读取文件中的前5行文本。如果是这样,您应该更正for子句。此外,您应该在处理完BufferedReader后释放它。它对我读取的每一行显示相同的错误5次,而不仅仅是最后一行。它显示第一个字符串的错误…您真的需要这样做吗d文件中的第一个字符串的五倍(因为您在循环体中创建了FileReader)
for (int i=0; i<5; i++) {
try {
BufferedReader reader = new BufferedReader(new FileReader("measurements.rtf"));
String line = null;
line= reader.readLine();
String[] dimensions = line.split("\\s"); \\ splitting the line into an array
String widthS = dimensions[0];
String heightS = dimensions[1];
System.out.println(widthS);
width = Integer.valueOf(widthS);
height = Integer.valueOf(heightS);
System.out.println(height + width);
}
catch (FileNotFoundException e){
System.out.println("Error! D:\nFile not found.");
System.out.println(e);
}
catch(Exception e){
System.out.println("Error"); // array out of bounds exception
System.out.println(e);
}
String fileName = "measurements.rtf";
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(fileName));
String line = null;
while((line = reader.readLine()) != null) {
System.out.println("Line: " + line);
String dimensions[] = line.split("\\s");
if(dimensions.length == 2) {
int width = Integer.parseInt(dimensions[0]);
int height = Integer.parseInt(dimensions[1]);
//...
} else {
//wrong content in line!
}
}
} catch (FileNotFoundException e) {
// Handle FileNotFoundException
} catch(IOException e) {
// Handle IOException
} catch(ArrayIndexOutOfBoundsException e) {
//Handle ArrayIndexOutOfBoundsException
}