我想将文本文件数据添加到 ArrayList。 这是我的文本文件
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
我使用空间分割数据。所以基本上有两个部分。 ID 和日期。 我创建了一个名为 Employee 的 bean 类,其中包含两个名为 user_id 和 mDate 的字符串。 EmployeeeArrayList 是我使用 Employee 类创建的 ArrayList。 问题是我无法向 Arraylist 添加值。仅最后一行数据插入到 ArrayList 中。例如:- 60000074 2016-10-26-06:01:04 。 四行 60000074 2016-10-26-06:01:04 。
这是我的代码。
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();
}
}
最佳答案
每次创建一个新的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();
}
原始代码的问题在于您重复使用了相同的对象emp
。这意味着您将同一对象重复插入到列表中。当您在循环的每次迭代中更改该对象的字段时,您会影响列表中的每个条目。通过将 emp
范围限定为循环,它不会被回收,并且您的代码应该按预期工作。
关于java - 将文本文件数据添加到 Arraylist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41761424/