简体   繁体   English

将文本文件数据添加到Arraylist

[英]Add text file data to a Arraylist

I want to add text file data to an ArrayList. 我想将文本文件数据添加到ArrayList。 This is my text file 这是我的文字档

60000115 2016-10-26-05:57:47                   
60000104 2016-10-26-05:58:27                   
60000082 2016-10-26-05:58:38                   
60000074 2016-10-26-06:01:04              

I am split data using space . 我正在使用space拆分数据。 So there are bassically two part. 因此,有两个部分。 Id and Date. 编号和日期。 I created a bean class called Employee with two String called user_id and mDate. 我创建了一个名为Employee的bean类,其中包含两个名为user_id和mDate的字符串。 employeArrayList is the ArrayList that i created using Employee class. employeeeArrayList是我使用Employee类创建的ArrayList。 Problem is I cannot add values to the Arraylist. 问题是我无法将值添加到Arraylist。 Only the last row data is inserting to the ArrayList. 仅最后一行数据插入到ArrayList中。 For ex :- 60000074 2016-10-26-06:01:04 . 例如: -60000074 2016-10-26-06:01:04 Four rows of 60000074 2016-10-26-06:01:04 . 四排60000074 2016-10-26-06:01:04

This is my code. 这是我的代码。

    for (File f : files) {
        FileInputStream fis;
        try {
            fis = new FileInputStream(f);
            BufferedReader in = new BufferedReader(new InputStreamReader(fis));

            String aLine;
            while ((aLine = in.readLine()) != null) {
                String[] tokens = aLine.split(" ");

                emp.setUser_id(tokens[0]);
                emp.setmDate(tokens[1]);
                employeArrayList.add(emp);

                out.write(aLine);
                out.newLine();

            }

            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Create a new Employee object each time: 每次创建一个新的Employee对象:

while ((aLine = in.readLine()) != null) {
    String[] tokens = aLine.split(" ");

    Employee emp = new Employee();
    emp.setUser_id(tokens[0]);
    emp.setmDate(tokens[1]);
    employeArrayList.add(emp);

    out.write(aLine);
    out.newLine();
}

The problem with your original code is that you were reusing the same object emp . 原始代码的问题在于,您正在重用同一对象emp This means that you were inserting the same object repeatedly into the list. 这意味着您将同一对象重复插入列表中。 And when you changed the fields of that object in each iteration of the loop, you affected every entry in the list. 当您在循环的每次迭代中更改该对象的字段时,都会影响列表中的每个条目。 By scoping emp to the loop, it won't be recycled and your code should work as intended. 通过将emp限定在循环范围内,它将不会被回收,并且您的代码应按预期工作。

The problem is that you keep updating the same emp object over and over again. 问题是您不断重复 更新同一emp对象。

You have to create a new one for each iteration; 您必须为每个迭代创建一个新的 and add that. 并添加。

Besides: you should only use "beans" with setters for core properties when using frameworks that need them. 此外:在使用需要属性的框架时,仅应将带有设置器的 “ beans”用于核心属性。

In other words: your bean class should better look like 换句话说:您的bean类最好看起来像

public class EmplyoeeBeen {
  private final String id;
  private final String date;

  public EmplyoeeBeen(String id, String date) {
    this.id = id;
  ...

And you only have getters on that class, no setters! 而且您在该课程上只有吸气剂 ,没有吸气剂 And: you probably want nice equals/hashCode methods, too. 并且:您可能也想要漂亮的equals / hashCode方法。

Finally: be consistent about naming: do not use "_" underscores (they only go into CONSTANT_NAMES); 最后:在命名上要保持一致:不要使用“ _”下划线(它们只能输入CONSTANT_NAMES); and either use prefixes like "m" + fieldname ... all the time; 要么一直使用“ m” +字段名...之类的前缀; or never. 或永远不会。 But dont go for userId and mDate! 但是请不要使用userId和mDate!

But the most important thing: avoid stringified typing. 但最重要的是:避免字符串化输入。 What I mean is: an ID is not a string. 我的意思是:ID 不是字符串。 A date is not a date. 日期不是日期。 When your fields carry a meaning; 当您的字段具有意义时; then use **classes to represent them that carry that meaning, too. 然后使用**类来表示也具有该含义的 For example you could invent your own Id class; 例如,您可以发明自己的Id类; and for sure: you would want to turn the date string into a real Date object. 并且可以肯定:您希望将日期字符串转换为真实的Date对象。

This is because of you are not creating new employee object each time. 这是因为您不是每次都创建新的员工对象。 change your code like below, so that it will not take same object each time 像下面那样更改代码,以便每次都不会使用相同的对象

for (File f : files) {
        FileInputStream fis;
        try {
            fis = new FileInputStream(f);
            BufferedReader in = new BufferedReader(new InputStreamReader(fis));

            String aLine;
            while ((aLine = in.readLine()) != null) {
                String[] tokens = aLine.split(" ");
                Employee emp=new Employee(); //create new object of employee
                emp.setUser_id(tokens[0]);
                emp.setmDate(tokens[1]);
                employeArrayList.add(emp);

                out.write(aLine);
                out.newLine();

            }

            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

There is no need to create tokens variable each time. 无需每次都创建令牌变量。 As String is immutable class you can reassign the value directly. 由于String不可变的类,因此您可以直接重新分配值。

String[] tokens = null;
for (File f : files) {
    FileInputStream fis;
    try {
        fis = new FileInputStream(f);
        BufferedReader in = new BufferedReader(new InputStreamReader(fis));
        String aLine;
        while ((aLine = in.readLine()) != null) {
            Employee emp = new Employee();
            tokens = aLine.split(" ");
            emp.setUser_id(tokens[0]);
            emp.setmDate(tokens[1]);
            employeArrayList.add(emp);

            out.write(aLine);
            out.newLine();

        }

        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Also create the Employee object each time for every line. 还要为每行每次创建Employee对象。

Another best way is to save your data in such a way that you can directly save it to bean. 另一个最佳方法是保存数据,以便可以直接将其保存到bean。 Save in JSON format. 以JSON格式保存。 And parse that data using GSON . 然后使用GSON解析该数据。 You can use array of user and Data as ArrayList in Bean. 您可以在Bean中将用户数组和数据用作ArrayList

 Please Try This List <String,String> emp = new ArrayList<String,String>(); emp.add(tokens[0],tokens[1]); 

Issue : You are using same object by changing the values. 问题:您正在通过更改值来使用同一对象。 It will reflect the latest values but all of them in that array list will point the single object in Memory. 它会反映最新的值,但是该数组列表中的所有值都将指向“内存”中的单个对象。

1.Create the Employee been inside the loop so that you can create new object for each iteration. 1.在循环内创建Employee,以便您可以为每次迭代创建新对象。

  1. Clone the employee object and add it into the list 克隆员工对象并将其添加到列表中

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

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