繁体   English   中英

使用JFileChooser打开txt文件并填充ArrayList

[英]Open txt file using JFileChooser and populate an ArrayList

我有一个具有ID,名称,地址和状态实例变量的Person类

  • ID没有设置器(mutator)方法
  • 名称,地址和状态实例变量同时具有setter和getter方法-要读取的txt文件以逗号分隔

我想使用JFileChooser打开一个txt文件,然后通过在线阅读来对Person类类型ArrayList进行化伪。 我被堆叠以将读入ID设置为Person对象,这是读入并填充arraylist的方法

public static ArrayList<Person> load(String fileName) throws IOException {
    ArrayList<person> lines = null;
    BufferedReader reader;
    try {
        JFileChooser chooser = new JFileChooser();
        chooser.setDialogTitle("Load which file?");
        int result = chooser.showOpenDialog(null);
        if (result == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();
            if (file != null) {
                fileName = file.getCanonicalPath();
                reader
                        = new BufferedReader(new FileReader(fileName));
                lines = new ArrayList<>();

                String line = reader.readLine();
                String data[];
                while ((line = reader.readLine()) != null) {
                    data = line.split(",");
                    Person s = new Person();


                     s.setName(data[0]);
                     s.setAddress(data[1]);
                    s.setState(data[2]);

                    //I got stack how to set ID bcs it has no set method

                    s.getAddress();                                   
                    s.getName();
                    s.getState();

                    lines.addAll(Arrays.asList(s));
                }
                reader.close();
                return lines;
            }
        }

    } catch (FileNotFoundException exp) {
        exp.printStackTrace();
    } catch (IOException exp) {
        exp.printStackTrace();
    }
    return lines;
}

}

如果您决定在分配ID后不想更改ID,则可以像下面这样重载类构造函数

public Person(int id){
    this.id = id;
}

然后在你的方法里面做

data = line.split(",");
Person s = new Person(whatever_if_you_wanana_set);

如果没有使用ID setter或构造方法,则无法设置ID 而且你为什么用

lines.addAll(Arrays.asList(s));

由于sPerson的对象,因此您可以简单地调用lines.add(s); 将人员对象添加到列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM