java - 数组越界异常

标签 java string split

我的计算机中有一个文本文件,我正在从我的 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

在使用以下代码从记事本中读取此内容时,我得到数组超出范围的异常。在调试时,我得到了 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());
    }
}

最佳答案

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

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

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

关于java - 数组越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17587935/

相关文章:

java - 如何使用 AutoIt 设置 Internet Explorer 选项?

java - 什么应该与 Java 对象同步

javascript - .reduce 返回 concat 而不是总和

c#-Windows 窗体 - 如何在列表框中找到 href 更多链接?

python - 我文本中的分隔符是什么

java - 询问嵌套 for 循环内的 while 循环

java - 在 Java 中确定文件相对于其他文件

java - 摩尔斯转英语程序中的 Java 输出不正确

vb.net - 在 VB.Net 中,使用静态定义的常量(与等效的字符串文字相比)是否可以提高效率?

r - 将数据框拆分为数据框列表,但如何重新合并?