【问题标题】:Array out of bound exception数组越界异常
【发布时间】:2013-07-11 07:54:31
【问题描述】:

我的计算机中有一个文本文件,我正在从我的 java 程序中读取它,我想建立一些标准。这是我的记事本文件:

   #Students
   #studentId   studentkey  yearLevel   studentName token   
   358314           432731243   12          Adrian      Afg56       
   358297           432730131   12          Armstrong   YUY89       
   358341           432737489   12          Atkins      JK671   

        #Teachers
        #teacherId  teacherkey    yearLevel teacherName token   
        358314          432731243   12          Adrian      N7ACD       
        358297          432730131   12          Armstrong   EY2C        
        358341          432737489   12          Atkins      F4NGH

在使用以下代码从记事本中读取此内容时,我得到 Array out of bound 异常。在调试时,我得到 strLine.length() 的“ #Students”值。 任何人都可以帮助解决这个问题吗?

private static Integer STUDENT_ID_COLUMN = 0;
private static Integer STUDENT_KEY_COLUMN = 1;
private static Integer YEAR_LEVEL_COLUMN = 2;
private static Integer STUDENT_NAME_COLUMN = 3;
private static Integer TOKEN_COLUMN = 4;

public static void main(String[] args) {
    ArrayList<String> studentTokens = new ArrayList<String>();

    try {
        // Open the file that is the first
        // command line parameter
        FileInputStream fstream = new FileInputStream("test.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
        String strLine;
        // Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            strLine = strLine.trim();

            if ((strLine.length()!=0) && (strLine.charAt(0)!='#')) {
                String[] students = strLine.split("\\s+");
                studentTokens.add(students[TOKEN_COLUMN]);
            }


        }

        for (String s : studentTokens) {
            System.out.println(s);
        }

        // Close the input stream
        in.close();
    } catch (Exception e) {// Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }
}

【问题讨论】:

  • notepad 是工具而不是文件,您正在从文本文件中读取。
  • 我刚刚使用提供的数据运行了您的代码,没有出现任何错误。您确定您使用的是同一组数据吗? (在文本文件中)
  • BufferedReader br = new BufferedReader(new InputStreamReader(fstream, "UTF8"));帮助了我

标签: java string split


【解决方案1】:

考虑到字符集,也许该文件被认为是 Unicode,但您要的是 ASCII 吗?你可以在这里改变它:

BufferedReader br = new BufferedReader(new InputStreamReader(in, charakterset));

这可能会有所帮助:Java InputStream encoding/charset

【讨论】:

    【解决方案2】:

    您似乎遇到了一些编码问题。以相同的格式保存和读取文件。最好使用 UTF-8。使用构造函数new FileInputStream(&lt;fileDir&gt;, "UTF8")进行读取。
    How to save a file in unicode

    【讨论】:

    • 文件格式为UTF8。您可以将文本文件发送到 abtawte@gmail.com 吗?
    • 您是否尝试实施这些更改?如果您的文件格式是UTF-8,它应该可以工作。不幸的是,我目前无法访问网络邮件。
    • BufferedReader br = new BufferedReader(new InputStreamReader(fstream, "UTF8"));帮助了我
    【解决方案3】:

    您的文件的编码可能与您正在读取的内容不同。

    找出文件的编码或将其转换为UTF8,然后在您的代码中使用如下编码读取它。

    您还应该将strLine.charAt(0)!='#' 更改为!strLine.contains("#"),除非它保证是第一个字符并且可能出现在其他字段中

    对于你捕获的任何异常,调用 printStackTrace() 也是一个好主意

    public static void main(String[] args) {
       ArrayList<String> studentTokens = new ArrayList<String>();
    
       try {
           // Open the file that is the first
           // command line parameter
           FileInputStream fstream = new FileInputStream(new File("C:\\Fieldglass\\workspace-Tools\\Tools\\src\\tools\\sanket.txt"));
    
      // ------ See below, added in encoding, you can change this as needed if not using utf8
           BufferedReader br = new BufferedReader(new InputStreamReader(fstream, "UTF8"));
    
           String strLine;
           // Read File Line By Line
           while ((strLine = br.readLine()) != null) {
               strLine = strLine.trim();
    
               if ((strLine.length()!=0) && (!strLine.contains("#"))) {
                   String[] students = strLine.split("\\s+");
                   studentTokens.add(students[TOKEN_COLUMN]);
               }
           }
    
           for (String s : studentTokens) {
               System.out.println(s);
           }
    
           // Close the input stream
           fstream.close();
           br.close();  // dont forget to close your buffered reader also
       } catch (Exception e) {// Catch exception if any
           e.printStackTrace();
           System.err.println("Error: " + e.getMessage());
       }
    }
    

    您可以在此处查找Java supported encodings(从 1.5 开始)

    【讨论】:

      【解决方案4】:

      您提供的信息不准确。

      使用以下代码从记事本中读取此内容时,我得到 Array out of bound 异常。

      如果代码和输入如您所说,我看不出这怎么可能。我能看到的唯一可以抛出ArrayIndexOutOfBoundsException 的地方是这一行:

        students[TOKEN_COLUMN]
      

      但我对您的代码和输入的阅读是,每条输入线都有 5 个字段。拆分时,将为您提供一个包含 5 个元素的数组,students[TOKEN_COLUMN] 将起作用。

      IMO,程序或输入与您描述的不同。 (我的猜测是您的输入行少于 5 个字段。)

      在调试时,我得到 strLine.length() 的“ #Students”值。

      这太离奇了,令人难以置信。 strLine.length() 返回一个 int。您向我们展示的是一个字符串。


      实际上,我对正在发生的事情有所了解。如果"  #Students"strLine 的值(不是strLine.length() !!)那么你已经设法在文件的开头得到了一些垃圾。当您的代码对此进行检查时,第一个字符 不会 是“#”,并且该行将显示为 2 个字段而不是 5 个。这将导致异常...

      而且我想我知道那些垃圾是从哪里来的。它是一个 UTF-8 字节顺序标记,由记事本插入到文件的开头......因为您将文件保存为 UTF-8。然后使用 CP1252 读取文件 ...(我认为)这是您系统的默认字符集。

      教训:不要使用记事本。使用真正的编辑器。

      参考:https://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-18
        • 2016-08-03
        • 2016-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多