【发布时间】:2020-11-04 21:32:14
【问题描述】:
我有一个 csv 文件,其中包含一些这种格式的数据:
id,first,last,city
1,john,doe,austin
2,jane,mary,seattle
到目前为止,我正在使用以下代码读取 csv:
String path = "./data/data.csv";
Map<Integer, User> map = new HashMap<>();
Reader reader = Files.newBufferedReader(Paths.get(path));
try (CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT)) {
List<CSVRecord> csvRecords = csvParser.getRecords();
for(int i=0; i < csvRecords.size(); i++){
if(0<i){//skip over header
CSVRecord csvRecord = csvRecords.get(i);
User currentUser = new User(
Double.valueOf(csvRecord.get(0)).intValue(),
Double.valueOf(csvRecord.get(1)),
Double.valueOf(csvRecord.get(2)),
Double.valueOf(csvRecord.get(3))
);
map.put(currentUser.getId(), currentUser);
}
}
} catch (IOException e){
System.out.println(e);
}
获取正确的值,但如果这些值的顺序不同,比如 [city,last,id,first],它将被错误地读取,因为读取是使用顺序 [id,first,last] 硬编码的,城市]。 (用户对象也必须按照 id、first、last、city 的确切顺序创建字段)
我知道我可以使用 'withHeader' 选项,但这也需要我提前定义标题列顺序,如下所示:
String header = "id,first,last,city";
CSVParser csvParser = new CSVParser(reader, CSVFormat.EXCEL.withHeader(header.split(",")));
我也知道有一个built in function getHeaderNames(),但只有在我已经将它们作为字符串传入之后才会获取标题(再次进行硬编码)。因此,如果我传入标题字符串“last,first,id,city”,它将在列表中完全返回。
有没有办法将这些位组合起来以读取 csv,无论列顺序是什么,并使用按顺序传递的字段(id、first、last、city)定义我的“用户”对象?
【问题讨论】:
标签: java csv parsing apache-commons