Reading and writing CSV in Java can be very simple by the use of some well known and stable CSV library. One can write CSV using core java classes very easily for reading CSV can be problematic as there are many variations in CSV.
CSV is one of the most common data formats for exporting and importing data. As the name suggests a comma-separated value, where data is written in columns separated by a comma. But it is not always true as there are many vendors who use different char or things to separate columns like tab, a combination of char, or some special character.
You can check different CSV formats which are supported by Apache Commons CSV library.
- DEFAULT
- EXCEL
- POSTGRESQL_CSV
- POSTGRESQL_TEXT
- TDF
- INFORMIX_UNLOAD
- INFORMIX_UNLOAD_CSV
- MYSQL
- RFC4180
- ORACLE
Java Libraries for CSV
There are many libraries available for CSV operation in java
- commons-csv Wider format support
- Fast CSV Fastest
- Super CSV
- Open CSV
- Java CSV
There might be even more libraries available. So you can choose based on your requirement.
Example to use Commons- CSV library
You can add this library by maven or Gradle dependency.
Maven:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-csv</artifactId> <version>1.8</version> </dependency>
Gradle:
// https://mvnrepository.com/artifact/org.apache.commons/commons-csv compile group: 'org.apache.commons', name: 'commons-csv', version: '1.8'
Read CSV example using Apache Commons CSV
// Read excel csv final File file = new File("csv-java\\src\\main\\resources\\sample.csv"); try (final CSVParser p = CSVParser.parse(file, Charsets.UTF_8, CSVFormat.EXCEL)) { final List<CSVRecord> resords = p.getRecords(); for (final CSVRecord csvRecord : resords) { for (int i = 0; i < csvRecord.size(); i++) { System.out.print(csvRecord.get(i) + " "); } System.out.println(""); } }
There are many other methods which provide the ability to read comment, header text and also manipulate data in different collections like MAP etc.
Write CSV file example
try (Writer wr = new FileWriter("my.csv")) { final CSVPrinter p = new CSVPrinter(wr, CSVFormat.POSTGRESQL_CSV); for (int i = 1; i < 11; ++i) { for (int j = 0; j < 4; ++j) { p.print(i + 10 * j); } p.println(); } }
Fast CSV Library Example
You can add this library using maven or Gradle dependency
Maven:
[xm]
de.siegmar
fastcsv
1.0.3
[/xml]
Gradle
// https://mvnrepository.com/artifact/de.siegmar/fastcsv compile group: 'de.siegmar', name: 'fastcsv', version: '1.0.3'
For example, you can check the GIT hub page of Library
FastCSV read and write example
Super CSV Java Lib
To use super CSV you should refer it’s a Super CSV, it has all the required resources like downloads, examples, and API documentation, etc.