【发布时间】:2020-04-02 08:25:19
【问题描述】:
我有一个项目,我应该在其中将对象写入 CSV 文件。我目前正在使用 ICsvBeanWriter ,但每次传递一条新记录时,它也会写入标题。从文件中读取时会产生问题。
以下分别是读写方法:
public static ArrayList<communication> readCSV() throws IOException {
ArrayList<communication> fileText = new ArrayList<>();
ICsvBeanReader beanReader = new CsvBeanReader(new FileReader("products.csv"), CsvPreference.STANDARD_PREFERENCE);
String[] header = beanReader.getHeader(true);
CellProcessor[] processors = new CellProcessor[]{
new ParseDouble(), // Distance
new ParseDouble(), // Efficiency
new ParseDouble(),// fuel
new ParseDouble(),// total
};
communication com;
while ((com = beanReader.read(communication.class, header, processors)) != null) {
fileText.addAll(Collections.singletonList(com));
}
return fileText;
}
public static void writeCSV(double tripDistance, double fuelEfficiency, double costOfFuel, double totalCost) throws Exception {
// create a list of employee
List<communication> EmployeeList = new ArrayList<>();
EmployeeList.add(new communication(tripDistance, fuelEfficiency, costOfFuel, (Math.round(totalCost * 100.0) / 100.0)));
ICsvBeanWriter beanWriter = new CsvBeanWriter(new FileWriter("products.csv",true),
CsvPreference.STANDARD_PREFERENCE);
String[] header = new String[]{"TripDistance", "FuelEfficiency", "FuelCost", "Total"};
beanWriter.writeHeader(header);
CellProcessor[] processors = new CellProcessor[]{
new ParseDouble(), // Distance
new ParseDouble(), // Efficiency
new ParseDouble(),// fuel
new ParseDouble(),// total
};
for (communication com : EmployeeList) {
beanWriter.write(com, header, processors);
}
beanWriter.close();
}
我想要一种跳过写入或读取标题的方法,或者创建删除所有标题行的方法(跳过第一行)。
这是出现的错误:
org.supercsv.exception.SuperCsvCellProcessorException: 'TripDistance' could not be parsed as a Double
processor=org.supercsv.cellprocessor.ParseDouble
【问题讨论】: