【问题标题】:Java - ArrayIndexOutOfBoundsException while inputting information from a text file [duplicate]Java - 从文本文件输入信息时出现 ArrayIndexOutOfBoundsException [重复]
【发布时间】:2015-07-26 18:19:22
【问题描述】:

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

戈登弗里曼 27

阿德里安·谢泼德 22

巴尼卡尔霍恩 19

爱丽克斯·万斯 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]);

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

谢谢。 :)

【问题讨论】:

    标签: java exception-handling text-files indexoutofboundsexception filereader


    【解决方案1】:

    我认为您的 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
    

    【讨论】:

      【解决方案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.");    
                  }
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-15
        • 2020-06-13
        • 2018-08-13
        相关资源
        最近更新 更多