简体   繁体   中英

Add text file data to a Arraylist

I want to add text file data to an 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 . So there are bassically two part. Id and Date. I created a bean class called Employee with two String called user_id and mDate. employeArrayList is the ArrayList that i created using Employee class. Problem is I cannot add values to the Arraylist. Only the last row data is inserting to the ArrayList. For ex :- 60000074 2016-10-26-06:01:04 . Four rows of 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:

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 . 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.

The problem is that you keep updating the same emp object over and over again.

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.

In other words: your bean class should better look like

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.

Finally: be consistent about naming: do not use "_" underscores (they only go into CONSTANT_NAMES); and either use prefixes like "m" + fieldname ... all the time; or never. But dont go for userId and mDate!

But the most important thing: avoid stringified typing. What I mean is: an ID is not a string. 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; and for sure: you would want to turn the date string into a real Date object.

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[] 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.

Another best way is to save your data in such a way that you can directly save it to bean. Save in JSON format. And parse that data using GSON . You can use array of user and Data as ArrayList in Bean.

 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. Clone the employee object and add it into the list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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