java:从文本文件中读取并创建它的对象并添加到集合然后排序

时间:2013-06-02 05:39:06

标签: java

我想做的是:

  1. 创建一个具有任何私有字段的Employee类 该文件。
  2. 从文件夹中的文件(有150个文件)中读取内容 并为每个文件创建员工对象。
  3. 存储在集合中创建的Employee对象
  4. 创建根据的方式对员工集合进行排序的方法 不同的字段按升序和降序排列。
  5. 我前三行的代码是:

    package com.fulcrum.emp;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    import java.util.Scanner;
    
    public class TestingColections {
    
        public static void main(String[] args) {
    
            File folder = new File("D:\\employee files");
            File[] listOfFiles = folder.listFiles();
            ArrayList<Employee> emp = null;
            int id = 0;
            String name = null;
            int age = 0;
            for (File file : listOfFiles) {
    
                try {
                    Scanner scanner = new Scanner(file);
    
                    String tokens = "";
                    String[] newtokens = null;
    
                    while (scanner.hasNext()) {
    
                        tokens = tokens.concat(scanner.nextLine()).concat(" ");
    
                        tokens = tokens.replace("=", "|");
                        newtokens = tokens.split("[|\\s]");
    
                    }
    
                    id = Integer.parseInt(newtokens[1]);
                    name = (newtokens[3] + " " + newtokens[4]);
                    age = Integer.parseInt(newtokens[6]);
    
                    emp = new ArrayList<Employee>();
    
                    emp.add(new Employee(id, name, age));
    
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
    
            }
    
        }
    
    }
    

    我的问题不仅仅是add()我尝试使用for循环在指定的索引中添加对象但是它给了IndexOutOfBoundException
    我怎么能这样做?有人可以帮助吗?
    而且我也想根据不同的领域对那些卑鄙的事情进行排序。
    请指导我。

2 个答案:

答案 0 :(得分:0)

如果没有堆栈跟踪,则无法知道,但IndexOutOfBoundsException听起来可能在以下几行:

id = Integer.parseInt(newtokens[1]);
name = (newtokens[3] + " " + newtokens[4]);
age = Integer.parseInt(newtokens[6]);

您相信newtokens至少有7个元素。

newtokens设置在这里

newtokens = tokens.split("[|\\s]");

因此,至少有一个输入文件中至少存在一行,其中该正则表达式产生的标记少于7个。

您是否检查过每个文件的每一行以确保其符合您预期的格式?

在解析这样的文件时,我更愿意先检查这些期望,然后抛出一个有意义的异常,以便更轻松地进行故障排除。

if (newtokens.length < 7) {
    throw new Exception("Too few tokens on line " + lineNumber + " of file " + file.getAbsolutePath());
}

答案 1 :(得分:0)

如果没有堆栈跟踪,很难理解问题是什么,但可能是这样: 您可以添加到ArrayList中的特定索引,但仅当此索引存在时才会添加。

如果您有一个大小为2的列表,则可以添加到索引0或索引1。

如果您的ArrayList没有任何成员,则只能添加到索引0.任何添加不存在索引的尝试都将导致您获得ArrayIndexOutOfBounds错误