Java - 从文本文件输入信息时出现 ArrayIndexOutOfBoundsException

Java - ArrayIndexOutOfBoundsException while inputting information from a text file

我是 Java(以及一般编程)的初学者。 我正在从包含以下文本的文本文件中输入信息:

Gordon Freeman 27

Adrian Shephard 22

Barney Calhoun 19

Alyx Vance 23

我在这个方法中得到了一个 ArrayIndexOutOfBoundsException:

private static void readFile2() {

    System.out.println("\nReading from file 2:\n");

    File file = new File("C:/Users/Reflex FN/Documents/IOTest2/text.txt");

    try {

        BufferedReader readFromFile = new BufferedReader(
                new FileReader(file));

        String read = readFromFile.readLine();

        while(read != null) {

            String[] readSplit = read.split(" ");
            int age = Integer.parseInt(readSplit[2]);
            System.out.println(readSplit[0] + " is " + age + " years old.");
            read = readFromFile.readLine();

        }

        readFromFile.close();

    } catch (FileNotFoundException ex) {

        System.out.println("File not found: " + ex.getMessage());

    } catch (IOException ex) {

        System.out.println("IO Exception: " + ex.getMessage());

    }

}

这是第一次成功;它打印:

戈登·弗里曼今年 27 岁。

但是,在打印任何其他内容之前,抛出了 ArrayIndexOutOfBoundsException。 我到底做错了什么? 异常的来源似乎是这一行:

int age = Integer.parseInt(readSplit[2]);

顺便说一句,我是新来的,所以我希望我没有把这个问题弄错。

谢谢。 :)

我认为您的 text.txt 文件中可能有新行。尝试将文件内容更改为 -

Gordon Freeman 27    
Adrian Shephard 22    
Barney Calhoun 19    
Alyx Vance 23

如果您在 Gordon Freeman 27 和 Adrian Shephard 23 之间换行。这将引发以下错误 -

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2

您的文本文件包含新行。在此声明中,您遇到异常

 int age = Integer.parseInt(readSplit[2]);

将您的代码更改为

   for (String read = readFromFile.readLine(); read != null; read = readFromFile.readLine()) {
            System.out.println(read+"a");
            if(!read.equals(""))//to check whether the line is empty
            {
            String[] readSplit = read.split("\s+");
            int age = Integer.parseInt(readSplit[2]);
            System.out.println(readSplit[0] + " is " + age + " years old.");    
            }
        }