Hanh Nguyen
Hanh Nguyen

Reputation: 135

CSV file contains empty line in the last

I am writing a list of object to CSV file using jackson-dataformat-csv lib. But when I open it, there is an empty line in the last. How can I remove this line when writting? Below is my code.

public static void writeAccountToFile(List<Map<String, Object>> list, String filePath) {
    System.out.println("Write data to csv file start");
    try {
        File file = new File(filePath);
        Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        CsvSchema schema = null;
        CsvSchema.Builder schemaBuilder = CsvSchema.builder();
        if (list != null && !list.isEmpty()) {
            for (String col : list.get(0).keySet()) {
                schemaBuilder.addColumn(col);
            }   
        } else {
              schemaBuilder.addColumn("test1");
              schemaBuilder.addColumn("test2");
        }
        schema = schemaBuilder.build().withLineSeparator("\r").withHeader();
        CsvMapper mapper = new CsvMapper();
        mapper.configure(CsvGenerator.Feature.STRICT_CHECK_FOR_QUOTING, true);
        mapper.writer(schema).writeValues(writer).writeAll(list);
        writer.flush();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Thanks for your reading.

Upvotes: 0

Views: 427

Answers (0)

Related Questions