🏠JavaOpenCSV for Reading and Writing CSV file in Java

OpenCSV for Reading and Writing CSV file in Java


Let’s take a look at reading and writing CSV files in java using OpenCSV with a few examples. First of all, OpenCSV is a CSV file (comma-separated values) parser library for Java. Unlike Apache Commons CSV library, this library is for advanced users who can deal with a little bit of config.

Adding OpenCSV to Java Project

Like many open-source libraries, you can download OpenCSV into your java project using build tools like Maven. For this, you need to include the following dependency in the <dependencies> section of your pom.xml in your Maven project.

<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>5.4</version> </dependency>
Code language: HTML, XML (xml)

At the time of writing, the current version is 5.4.

Read from CSV file using OpenCSV

Like other libraries, you can parse and read data from CSV files using OpenCSV. For example, here is a simple java example that reads reach row of a .csv file.

CSVReader reader = new CSVReader(new FileReader("employees.csv")); List<String[]> rows = reader.readAll(); for (String[] row : rows) { System.out.println(row[0] + "," + row[1] + "," + row[2] + "," + row[3]); }
Code language: Java (java)

As you can see, We read all the rows into a list and looped through the list to print each column as we need. You can also read each row line by line to avoid filling the memory.

//read line by line reader = new CSVReader(new FileReader("employees.csv")); String[] nextLine; while ((nextLine = reader.readNext()) != null) { System.out.println(nextLine[0] + "," + nextLine[1] + "," + nextLine[2] + "," + nextLine[3]); } reader.close();
Code language: Java (java)

OpenCSV can Read CSV rows into Java Objects

Yes, you can convert each row into a POJO with simple steps. So let’s take a look at that java example. For this, OpenCSV provides an intuitive yet powerful CsvToBeanBuilder implementation.

Lets say your employee.csv file looks like below.

FirstName,LastName,Email,Department Man,Sparkes,msparkes0@springhow.com,Engineering Dulcinea,Terzi,dterzi1@springhow.com,Engineering Tamar,Bedder,tbedder2@springhow.com,Legal Vance,Scouller,vscouller3@springhow.com,Sales Gran,Jagoe,gjagoe4@springhow.com,Business Development
Code language: plaintext (plaintext)

Now you need to create an Employee.java POJO and let OpenCSV know that it should use this class to convert the records into java objects.

public class Employee { public String firstName; public String lastName; public String email; public String department; //getters and setters @Override public String toString() { return "Employee{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", department='" + department + '\'' + '}'; } }
Code language: Java (java)

Note that the column headers in the CSV match the field names of the POJO class. Let’s write the code for converting csv records into objects.

List<Employee> employees = new CsvToBeanBuilder(new FileReader("employees.csv")) .withType(Employee.class) .build() .parse(); System.out.println(employees);
Code language: Java (java)

As you can see, the result is a list of employee. On printing the list, you can see that opencsv converted all data into Employee objects automatically.

OpenCSV converts rows into java objects

Furthermore, you can use different header names for columns and still match them to appropriate fields. For example, If your column header name is Contact and you want it to go to the email field, then you can amend your POJO like this.

public class Employee { public String firstName; public String lastName; @CsvBindByName(column = "Email") public String contact; ... ... }
Code language: Java (java)

There are also other binding annotations like @CsvBindByPosition and @CsvBindAndSplitByName etc.

Validation in Bean binding

While reading data using CsvToBeanBuilder, you can add validation annotations to your POJO classes. For example, You can mark a field as mandatory by setting @CsvBindByName(required = true).

Similarly, you can mark a field as expected to be a number or date. Here is a simple example.

public class MonitoringData { @CsvBindByName @CsvNumber("###.##") // 000.00 format public int value; @CsvBindByName @CsvDate("yyyy-MM-dd") // 1995-10-24 public Date capturedAt; public String metric; ... ... }
Code language: Java (java)

Writing CSV files from Data using OpenCSV in java

The writing CSV is as simple as reading that we have seen before. To write data into a CSV file, you would need a CSVWriter object. This object takes a Writer object. In our case, we will supply a FileWriter.

CSVWriter csvWriter = new CSVWriter(new FileWriter("list.csv")); csvWriter.writeNext(new String[]{"John", "Doe", "jdoe@example.com", "Sales"}); csvWriter.writeNext(new String[]{"Jane", "Doe", "jane.doe@example.com", "HR"}); csvWriter.close();
Code language: Java (java)

You can combine multiple lines into one using csvWriter.writeAll() variants.

List<String[]> lines = getRecordsAsList(); csvWriter = new CSVWriter(new FileWriter("list.csv")); csvWriter.writeAll(lines); csvWriter.close();
Code language: Java (java)

You can even write a SQL result set directly into a CSV file.

csvWriter = new CSVWriter(new FileWriter("list.csv")); Connection connection = DriverManager.getConnection(""); Statement stmt = connection.createStatement(); ResultSet resultSet = stmt.executeQuery("select * from employees"); csvWriter.writeAll(resultSet, true); csvWriter.close(); connection.close();
Code language: Java (java)

In the case of result sets, you can choose to include the column names as a header with a boolean parameter. Also, the column order will change based on how the query returned the results.

Writing list of java objects into CSV

Like we can read records in to java objects, OpenCSV can help write java objects into rows in a .csv file. For this, you need StatefulBeanToCsv object.

List<Employee> employees = getListOfEmployeesFromSomewhere(); Writer writer = new FileWriter("employees.csv"); StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer).build(); beanToCsv.write(employees); writer.close();
Code language: Java (java)

This approach is by far the most java friendly addition that is missing from other CSV libraries like Apache Commons CSV.

So far, we learned many ways to read and write CSV files using OpenCSV library in Java with examples. All of the examples from above are available at our GitHub repository.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *