从文件读取时ArrayIndexOutOfBoundsException

时间:2017-02-16 00:21:09

标签: java file exception

我有以下方法读取文件,其中 ID (int)和内容(字符串)由制表符分隔。我的方法逐行读取文件,并使用制表符分隔符,将 ID 和字符串解析为双向链接列表,如下所示:

knex('item').update({
  qtyonhand: knex.raw('?? + 1', ['qtyonhand'])
}).where('rowid',8)

当我运行它时,此方法在 Eclipse 中完美运行,但在使用 javac 并在终端中运行时,会出现此错误:

void readAndAssemble(String fileName)
    {
        Scanner sc;
        try
    {
        sc = new Scanner(new File(fileName));
        while (sc.hasNextLine())
        {
            String line = sc.nextLine();
            String lines[] = line.split("\t");
            int packetID = Integer.parseInt(lines[0]);
            // -----------------------------------------
            String packetContent = lines[1]; // gives error in terminal
            // -----------------------------------------
            DLLNode curr = header.getNext();
            DLLNode prev = header;
            while (packetID > curr.getPacketID())
            {
                prev = curr;
                curr = curr.getNext();
            } 
            DLLNode newNode = new DLLNode(packetID, packetContent, prev, curr);
            prev.setNext(newNode);
            curr.setPrev(newNode);

        }
        sc.close();
    } catch (FileNotFoundException e)
    {
        System.out.println("File does not exist");
    }

}

我的MessageAssembler类看起来像这样:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at DLL.readAndAssemble(DLL.java:40)
at MessageAssembler.main(MessageAssembler.java:11)

导致这种情况的原因是什么?

1 个答案:

答案 0 :(得分:1)

您的文件中的行似乎与您的理解不符。

尝试做

 String lines[] = line.split("\t");
 if (lines.length < 2) {
    System.err.println ("error with line " + line);
    continue;
 }

unix文件

上使用扫描仪似乎存在问题

    FileInputStream fstream = new FileInputStream("c:/temp/a.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

    String line;

    //Read File Line By Line
    while ((line = br.readLine()) != null)   {
      // Print the content on the console
      System.out.println (line);
      String [] lines = line.split ("\t");
      if (lines.length < 2) {
            System.err.println ("error with line " + line);
            continue;
         }        

    }

    //Close the input stream
    br.close();
相关问题