Read / Write CSV file in Java

If you want to work with Comma-separated Files (CSV) in Java, here’s a quick API for you. As Java doesn’t support parsing of CSV files natively, we have to rely on third party library. Opencsv is one of the best library available for this purpose. It’s open source and is shipped with Apache 2.0 licence which makes it possible for commercial use. Let’s us see different APIs to parse CSV file. Before that we will need certain tools for this example: 

Tools & Technologies

  1. Java JDK 1.5 or above
  2. OpenCSV library v1.8 or above (download)
  3. Eclipse 3.2 above (optional)

Let’s get started.

1. Reading CSV file in Java

We will use following CSV sample file for this example: File: sample.csv

COUNTRY,CAPITAL,POPULATION India,New Delhi, 1.21B People's republic of China,Beijing, 1.34B United States,Washington D.C., 0.31B
Code language: PHP (php)

Read CSV file line by line:

String csvFilename = "C:\\sample.csv"; CSVReader csvReader = new CSVReader(new FileReader(csvFilename)); String[] row = null; while((row = csvReader.readNext()) != null) { System.out.println(row[0] + " # " + row[1] + " # " + row[2]); } //... csvReader.close();
Code language: Java (java)

In above code snippet, we use readNext() method of CSVReader class to read CSV file line by line. It returns a String array for each value in row. It is also possible to read full CSV file once. The readAll() method of CSVReader class comes handy for this.

String[] row = null; String csvFilename = "C:\\work\\sample.csv"; CSVReader csvReader = new CSVReader(new FileReader(csvFilename)); List content = csvReader.readAll(); for (Object object : content) { row = (String[]) object; System.out.println(row[0] + " # " + row[1] + " # " + row[2]); } //... csvReader.close();
Code language: Java (java)

The readAll() method returns a List of String[] for given CSV file. Both of the above code snippet prints output: Output

COUNTRY # CAPITAL # POPULATION India # New Delhi # 1.21B People's republic of China # Beijing # 1.34B United States # Washington D.C. # 0.31B
Code language: PHP (php)

Use different separator and quote characters If you want to parse a file with other delimiter like semicolon (;) or hash (#), you can do so by calling a different constructor of CSVReader class:

CSVReader reader = new CSVReader(new FileReader(file), ';') //or CSVReader reader = new CSVReader(new FileReader(file), '#')
Code language: Java (java)

Also if your CSV file’s value is quoted with single quote (‘) instead of default double quote (“), then you can specify it in constructor:

CSVReader reader = new CSVReader(new FileReader(file), ',', '\'')
Code language: Java (java)

Also it is possible to skip certain lines from the top of CSV while parsing. You can provide how many lines to skip in CSVReader’s constructor. For example the below reader will skip 5 lines from top of CSV and starts processing at line 6.

CSVReader reader = new CSVReader(new FileReader(file), ',', '\'', 5);
Code language: Java (java)

2. Writing CSV file in Java

Creating a CSV file is as simple as reading one. All you have to do is it create the data list and write using CSVWriter class. Below is the code snippet where we write one line in CSV file.

String csv = "C:\\output.csv"; CSVWriter writer = new CSVWriter(new FileWriter(csv)); String [] country = "India#China#United States".split("#"); writer.writeNext(country); writer.close();
Code language: Java (java)

We created object of class CSVWriter and called its writeNext() method. The writeNext() methods takes String [] as argument. You can also write a List of String[] to CSV directly. Following is code snippet for that.

String csv = "C:\\output2.csv"; CSVWriter writer = new CSVWriter(new FileWriter(csv)); List<String[]> data = new ArrayList<String[]>(); data.add(new String[] {"India", "New Delhi"}); data.add(new String[] {"United States", "Washington D.C"}); data.add(new String[] {"Germany", "Berlin"}); writer.writeAll(data); writer.close();
Code language: Java (java)

We used writeAll() method of class CSVWriter to write a List of String[] as CSV file.

3. Mapping CSV with Java beans

In above examples we saw how to parse CSV file and read the data in it. We retrieved the data as String array. Each record got mapped to String. It is possible to map the result to a Java bean object. For example we created a Java bean to store Country information. Country.java – The bean object to store Countries information.

package net.viralpatel.java; public class Country { private String countryName; private String capital; public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } public String getCapital() { return capital; } public void setCapital(String capital) { this.capital = capital; } }
Code language: Java (java)

Now we can map this bean with Opencsv and read the CSV file. Check out below example:

ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy(); strat.setType(Country.class); String[] columns = new String[] {"countryName", "capital"}; // the fields to bind do in your JavaBean strat.setColumnMapping(columns); CsvToBean csv = new CsvToBean(); String csvFilename = "C:\\sample.csv"; CSVReader csvReader = new CSVReader(new FileReader(csvFilename)); List list = csv.parse(strat, csvReader); for (Object object : list) { Country country = (Country) object; System.out.println(country.getCapital()); }
Code language: Java (java)

Check how we mapped Country class using ColumnPositionMappingStrategy. Also the method setColumnMapping is used to map individual property of Java bean to the CSV position. In this example we map first CSV value to countryName attribute and next to capital.

4. Dumping SQL Table as CSV

OpenCSV also provides support to dump data from SQL table directly to CSV. For this we need ResultSet object. Following API can be used to write data to CSV from ResultSet.

java.sql.ResultSet myResultSet = getResultSetFromSomewhere(); writer.writeAll(myResultSet, includeHeaders);
Code language: Java (java)

The writeAll(ResultSet, boolean) method is utilized for this. The first argument is the ResultSet which you want to write to CSV file. And the second argument is boolean which represents whether you want to write header columns (table column names) to file or not.

Download Source Code

ReadWrite_CSV_Java_example.zip (356 KB)

View Comments

  • Hi SIr,

    I want to display one row data into another row with same values .
    e.g. first row contains same value after reading program out file will be 2 rows same values plzz help me

  • Hi SIr,
    I want to display one row data into another row with same values .
    e.g. first row contains same value after reading program output file will be 2 rows same values
    plzz help me..Thanks

    [code language="java"]Java source code[/code]

  • hi..
    I want to know about how to map csv file with database.my project on J2EE so please help me.how to view ,update ,upload,delete csv file .thank you.

  • Thank you for this post.

    A question: how would you deal with values that contain commas? For example if there's a company name Some Company, Inc.. The usual parsing will interpret the comma between company and Inc as separate values, and this throws everything off.

    I have no control over the csv file -- I need to work with it the way it is.

    Thanks!

  • man after a long search I found you, and I hope you'll relieve me of my frustration. Thing is I've .CSV files and .CSV data dumps from a website for which im an affiliate and when i'm trying to upload them to my wordpress website nothing is working!

    I just want to upload my .CSV and make galleries on my webpage, pls help me out with this; could you suggest any csv plugin that works with wordpress? I failed with everything available. I'm clueless!

    Thanks in advance

  • Hello Mr Patel

    I have to prepare a java tool which can combine multiple csv files into a single excel sheet where each of these csv file will represent a single worksheet of the combined excel file . Can you please help me in getting a little insight on the logical approach which will be involved in developing the road map of this tool . you please help me at the earliest .

    Regards
    Prag Tyagi

  • JavaOne 2013 is apparently being held at Hyderabad this year as well (8-9 May) at the same place guys…. They have also started accepting registrations (check this: http://bit.ly/YMPeJ8 )
    I am definitely going to attend the Java One again. Last time I had a chance to help people at NetBeans Booth, thanks to Java One Team for that great favor. I know, Java and NetBeans community will definitely attend this prestigious nd great conference this year too…..

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

5 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

5 years ago