我有一个 CSV 文件,我想使用 OpenCSV 的 csvreader 在 Java 中解析该文件。
为此,我创建了一个信息映射到的 bean 对象。我的有点长,所以这是我从教程中获得的示例:
package net.viralpatel.java;
public class Country {
private String countryName;
private String capital;
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public String getCapital() {
return capital;
}
public void setCapital(String capital) {
this.capital = capital;
}
}
我用来解析 CSV 文件并将信息映射到 Bean 的代码与此类似:
ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy();
strat.setType(Country.class);
String[] columns = new String[] {"countryName", "capital"};
strat.setColumnMapping(columns);
CsvToBean csv = new CsvToBean();
String csvFilename = "C:\\sample.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
List list = csv.parse(strat, csvReader);
问题是我的 CSV 不仅包含原始数据,还包含列标题和其他数据。对于列标题,我通过仅从特定行读取文件来解决问题:
CSVReader csvReader = new CSVReader(new FileReader(csvFilename), ';', '\'', 1);
(1是读取开始的行)
其他数据主要是文件末尾的(例如)整数列中的字符串。
例如,我有一个包含整数信息的“最大速度”列,紧挨着一个包含整数信息的“距离”列。但在“距离”列的末尾有总距离,因此字符串“total:”位于其旁边的“最大速度”列中。
我该怎么做才能确保读者忽略最后几行并只阅读上面的原始信息?
PS:我读取的 CSV 文件长度不同。所以说“在 X 行之后停止阅读”是行不通的。另一方面,“附录”行始终相同。所以说“停止读取文件末尾之前的两行”应该有效。
非常感谢您的帮助。
最佳答案
您始终可以下降到较低级别并在将原始字符串数组映射到 bean 之前检查原始字符串数组,如下所示:
ColumnPositionMappingStrategy<Country> strat = new ColumnPositionMappingStrategy<Country>();
strat.setType(Country.class);
String[] columns = new String[] {"countryName", "capital"};
strat.setColumnMapping(columns);
PublicProcessLineCsvToBean<Country> csv = new PublicProcessLineCsvToBean<Country>();
String csvFilename = "C:\\sample.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
List<Country> list = new ArrayList<Country>();
String [] row = csvReader.readNext(); //skip header
if(row == null) throw new RuntimeException("File is empty");
row = csvReader.readNext();
String [] nextRow = csvReader.readNext();
while(row != null) {
if(nextRow == null) break; //check what 'row' is last
if("Total:".equalsIgnoreCase(row[1])) break; //check column for special strings
list.add(csv.processLine(strat, row));
row = nextRow;
nextRow = csvReader.readNext();
}
并将 processLine 公开:
public static class PublicProcessLineCsvToBean<T> extends CsvToBean<T> {
@Override
public T processLine(MappingStrategy<T> mapper, String[] line) throws IllegalAccessException, InvocationTargetException, InstantiationException, IntrospectionException {
return super.processLine(mapper, line);
}
}
关于java - 使用 OpenCSV 仅部分解析 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35695348/