gpt4 book ai didi

Java List 不断添加最后一条记录,将其复制为文件中的记录数

转载 作者:搜寻专家 更新时间:2023-10-31 19:39:23 25 4
gpt4 key购买 nike

我的代码中发生了一件奇怪的事情,我只是不确定发生了什么。我有一个看起来像这样的文件:

id;state;city;total_pop;avg_temp
1;Florida;;120000;76
2;Michigan;Detroit;330000;54
3;New Jersey;Newark;;34

我的 java 解析器应该创建一个映射列表作为结果并返回。但唯一返回的是文件中重复文件行数的最后一条记录。有人可以查看我的代码并启发我了解发生了什么吗?提前谢谢你。

public class FileParserUtil {

public List<Map<String, String>> parseFile(String fileName, char seperator)
throws IOException {

CSVReader reader = new CSVReader(new FileReader(fileName), seperator);
Map<String, String> record = new HashMap<String, String>();
List<Map<String, String>> rows = new ArrayList<Map<String, String>>();

String[] header = reader.readNext();
String[] nextLine;

while ((nextLine = reader.readNext()) != null) {
for (int i = 0; i < header.length; i++) {
record.put(header[i], nextLine[i]);
}
System.out.println("--------Here is the record: ---------");
System.out.println(record);
rows.add(record);
System.out.println("--------Here are the rows: ---------");
System.out.println(rows);
}
reader.close();
return rows;

}
}

这是上面运行的主方法的控制台输出...

--------Here is the record: ---------
{id=1, avg_temp=76, state=Florida, total_pop=120000, city=}
--------Here are the rows: ---------
[{id=1, avg_temp=76, state=Florida, total_pop=120000, city=}]
--------Here is the record: ---------
{id=2, avg_temp=54, state=Michigan, total_pop=330000, city=Detroit}
--------Here are the rows: ---------
[{id=2, avg_temp=54, state=Michigan, total_pop=330000, city=Detroit}, {id=2, avg_temp=54, state=Michigan, total_pop=330000, city=Detroit}]
--------Here is the record: ---------
{id=3, avg_temp=34, state=New Jersey, total_pop=, city=Newark}
--------Here are the rows: ---------
[{id=3, avg_temp=34, state=New Jersey, total_pop=, city=Newark}, {id=3, avg_temp=34, state=New Jersey, total_pop=, city=Newark}, {id=3, avg_temp=34, state=New Jersey, total_pop=, city=Newark}]

最佳答案

我认为你忘记用新的空 map 替换 record,在它被添加到列表之后。你想要这样的东西:

rows.add(record);
record = new HashMap<String, String>();

关于Java List 不断添加最后一条记录,将其复制为文件中的记录数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19317940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com