Skip to main content
CSV Logo

CSV file reading and writing in Java using jCSV

CSV Logo

Overview

We are going to discuss the jCSV library. The jCSV library is a light-weight library for reading and writing a CSV files in Java. It was released in 2012 but it’s working perfectly. The tutorial will be used Java 8 Lambda expressions for looping. Anyway, you can use Java early version also.

Dependency

We need to the com.googlecode.jcsv dependency to the project.

for Maven

for Gradle

CSV File writing

Let’s say we have a model, it’s called Car.java.

Now, we’re ready to implement CSV writer. It’s called Writer.java

If you carefully look at the code, you can see the java class that name is CarCSVConverter.java. This class main responsibility is, convert Car object as you want and put data into the String array.

How to run it

Create an Object of Writer class and call the write() method.

You can see the data.csv file is created inside the project directory.

CSV File Reader

We use data.csv for reading also. Need to create a java class that called Reader.java.

Finally, need to implement a helper class for assembling.

How to run it

Entry Filter

Let’s say, you want to filter data while reading. For an example, we need only get cars which are Toyotas.

So that, need to implement a Filter class.

Then, change a CSVReader in the Reader.java.

Now, when you run the application, it will show only the Toyota car.

 


Related Post

17369total visits,4visits today

  • M98987

    Why aren’t strings quoted?
    The default strategy seems to indicate that strings should be quoted.

    • Damith Chathuranga

      I tried out with the DEFAULT and UK_DEFAULT strategy, then with custom strategy also.
      .strategy(new CSVStrategy(‘|’, ‘”‘, ‘#’, false, true)). But still generate without the quotes. Finally, I debugged it looks like a library issue. Thanks!

    • mydevgeek

      I tried out with the DEFAULT and UK_DEFAULT strategy, then with custom strategy also.
      .strategy(new CSVStrategy(‘|’, ‘”‘, ‘#’, false, true)). But still generate without the quotes. Finally, I debugged it looks like a library issue. Thanks!

RSS
Follow by Email
Facebook
Facebook
Google+
http://mydevgeek.com/csv-file-reading-writing-java-using-google-jcsv
Twitter