我的代码中发生了一件奇怪的事情,我只是不确定发生了什么。我有一个看起来像这样的文件:
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;
}
}
这是上面从 main 方法运行的控制台输出...
--------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}]