我有一个 csv 文件。我想从中提取特定的列。例如: 说,我有 csv:
id1,caste1,salary,name1
63,Graham,101153.06,Abraham
103,Joseph,122451.02,Charlie
63,Webster,127965.91,Violet
76,Smith,156150.62,Eric
97,Moreno,55867.74,Mia
65,Reynolds,106918.14,Richard
我如何使用 opencsv 只读取来自 header caste1 的数据?
最佳答案
Magnilex 和 Sparky 是正确的,CSVReader 不支持按列名读取值。但话虽如此,您可以通过两种方式做到这一点。
假设您有列名并且默认的 CSVReader 读取标题,您可以首先搜索标题的位置,然后从那里开始使用它;
private int getHeaderLocation(String[] headers, String columnName) {
return Arrays.asList(headers).indexOf(columnName);
}
所以你的方法看起来像(省略了很多你需要放入的错误检查)
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
int columnPosition;
nextLine = reader.readNext();
columnPosition = getHeaderLocation(nextLine, "castle1");
while ((nextLine = reader.readNext()) != null && columnPosition > -1) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[columnPosition]);
}
只有在您时间紧迫且您只关心一个专栏时,我才会执行上述操作。这是因为 openCSV 可以使用 CsvToBean
类和 HeaderColumnNameMappingStrategy
直接转换为具有与标题列名称相同的变量的对象。
因此,首先您将定义一个包含字段的类(实际上您只需要放入您想要的字段——多余的字段将被忽略,缺失的字段为 null 或默认值)。
public class CastleDTO {
private int id1;
private String castle1;
private double salary;
private String name1;
// have all the getters and setters here....
}
那么你的代码看起来像
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
HeaderColumnNameMappingStrategy<CastleDTO> castleStrategy = new HeaderColumnNameMappingStrategy<CastleDTO>();
CsvToBean<CastleDTO> csvToBean = new CsvToBean<CastleDTO>();
List<CastleDTO> castleList = csvToBean.parse(castleStrategy, reader);
for (CastleDTO dto : castleList) {
System.out.println(dto.getCastle1());
}
关于java - 如何读取 opencsv 中的特定 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31414120/