[JAVA] CSV output with Apache Commons CSV

Introduction

It is not so difficult to output CSV, but there are some specifications, and if you output without knowing it, you may end up ignoring the specifications. Or rather, I've tried something close. You can check the specification itself in wiki or Official specification. Java publishes a library for Apache to read and write CSV, so I summarized the output using this. Do not read.

Official manual

Basic

http://commons.apache.org/proper/commons-csv/

Javadoc http://commons.apache.org/proper/commons-csv/apidocs/index.html

About initial settings

https://mvnrepository.com/artifact/org.apache.commons/commons-csv When using Maven or Gradle, you can get groupId etc. by referring to the above. For the time being, the official has released Download Link, so you should be able to download it from here and run it (unconfirmed). ..

Basic usage

Simple example is described in the CSV Printer of Javadoc.

Description example


try (CSVPrinter printer = new CSVPrinter(new FileWriter("csv.txt"), CSVFormat.EXCEL)) {
    printer.printRecord("id", "userName", "firstName", "lastName", "birthday");
    printer.printRecord(1, "john73", "John", "Doe", LocalDate.of(1973, 9, 15));
    printer.println();
    printer.printRecord(2, "mary", "Mary", "Meyer", LocalDate.of(1985, 3, 29));
} catch (IOException ex) {
    ex.printStackTrace();
}

Output example


id,userName,firstName,lastName,birthday
1,john73,John,Doe,1973-09-15

2,mary,Mary,Meyer,1985-03-29

Explanation below.

CSVPrinter printer = new CSVPrinter(new FileWriter("csv.txt"), CSVFormat.EXCEL)

CSVPrinter is an instance for CSV output. CSVFormat.EXCEL is the format for CSV output. DEFAULT basically based on RFC4180 (but there are some differences ) And EXCEL according to the specifications of the EXCEL file. I think there are many other things, so check Official Javadoc Good to see. You can see the difference between them by checking the Javadoc, but there are some settings that are only related to reading CSV.

printer.printRecord("id", "userName", "firstName", "lastName", "birthday");
printer.printRecord(1, "john73", "John", "Doe", LocalDate.of(1973, 9, 15));
printer.println();
printer.printRecord(2, "mary", "Mary", "Meyer", LocalDate.of(1985, 3, 29));

One line of data is output by printRecord. Since the argument is ʻObject, it can receive other than character strings. Line break with println. If the value contains a delimiter, it will be output according to the format (if CSVFormat.EXCEL is used, the value will be output surrounded by "`).

Delimiter in value


printer.printRecord("te,st", "test");

Output example when the value has a delimiter


"te,st",test

About other usage

output

By using the print method, 1 It is possible to output not for each record but for each value. If you execute it continuously, the delimiter will be inserted automatically, but even if you try to use it at the same time as the printRecord method on the same line, the delimiter will not be inserted.

Combined use of print and printRecord


printer.print("test1");
printer.print("test2");
printer.printRecord("test3", "test4");

output


test1,test2test3,test4

PrintComment method that outputs other comments [PrintRecords method] that outputs multiple lines instead of one record (http://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVPrinter.html#printRecords-java.lang .Object ...-) Something (printRecords is ResultSet Can be taken as an argument), so it is better to use it properly as needed.

CSV format

Depending on how you use CSVFormat, you can modify the CSV format in advance. In the example below, the header line is added in advance and the delimiter is changed to the tab character.

CSV format correction


CSVPrinter printer =
    CSVFormat.DEFAULT.withHeader("Header 1", "Header 2", "Header 3").withDelimiter('\t').print(writer);
printer.printRecord("a", "b", "c");

Output example


Header 1 Header 2 Header 3
a	b	c

The header line is added by the withHeader method, and the delimiter is changed by the withDelimiter method. The last print method is for getting an instance of CSVPrinter. Since there are many other things, you can use them to change the format of the CSV you create, but it seems that creating a CSV that you do not understand will not prevent it from being read as CSV by other applications. I want to.

in conclusion

I want to handle CSV with standard functions.

Recommended Posts

CSV output with Apache Commons CSV
Customize the output with Wagby's CSV download function
CSV import with BOM
Output FizzBuzz with stream
Convert large XLSX files to CSV with Apache POI
I tried to read and output CSV with Outsystems
Repeated sample with Apache Freemarker
Check CSV value with RSpec
Start Apache Solr with Embedded.
Apache Commons BeanUtils fit point
Access Apache Kafka with Micronaut
Output multiplication table with Stream
Control log output with Doma2
Output "Izumi Oishi" with dokojava
Supports 0 drop in CSV output
Csv output processing using super-csv
Output Rails Routes as csv
Manipulate Excel with Apache POI
Output Excel with formulas with XlsMapper
Excel output using Apache POI!
Output characters like conversation with JavaFX
Easy JDBC calls with Commons DbUtils
Circuit Breaker Pattern with Apache Camel
Output test coverage with clover + gradle
[Ruby on Rails] CSV output function
Download large files with Apache JMeter
Easy Pub/Sub messaging with Apache Kafka
Output PDF and TIFF with Java 8
Restart apache with docker php-apache image
FileUpload with Rest on Apache Wicket
[Linux] Start Apache container with Docker