java - 使用 CsvBeanReader 时有没有办法跳过标题?

标签 java supercsv

我有一个项目,我应该将对象写入 CSV 文件。我目前正在使用 ICsvBeanWriter,但每次传递新记录时,它也会写入 header 。从文件读取时会产生问题。

下面分别是读取和写入的方法:

    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

最佳答案

这些代码行创建一个 header :

String[] header = new String[]{"TripDistance", "FuelEfficiency", "FuelCost", "Total"};
beanWriter.writeHeader(header);

我想你可以从代码中删除它们。

关于java - 使用 CsvBeanReader 时有没有办法跳过标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60987176/

相关文章:

java - 标签和面板透明度问题

java - 如何使用 SuperCsv 隔离类的实例?

java - 如何配置 Super CSV 以引用除列名之外的所有值?

java - 如何使用类路径指定文件位置?

java - 寻找 java SFTP 现代库,而不是 jsch

java - 在Java中如何通过递归计算出某个字母在字符串中出现了多少个?

java - 如何在 Jython/Java 代码中提供 python 包路径?

Java 创建 100MB 压缩 csv 文件性能问题

java - 如何使 Android Google 登录按钮仅登录而不使用 FirebaseAuth 注册?