How to read/write CSV file to Map in java

Posted on Updated on

As you see in last article, how to read a CSV file into Java object with the help of Jackson API. In this article, we will see how to write a list of Map ( List<Map<String,String>> ) into a CSV file in your machine and again read it through with Jackson API.

Add this dependency in your pom.xml file to used Jackson API in your application.

<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-csv</artifactId>
  <version>2.7.0</version>
</dependency>

 

Below are a sample example of reading or writing a CSV file with the help of Jackson API, which makes it very easy to write or read the CSV file into Java Object.

 


package com.example;

import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

import java.io.*;
import java.util.*;

/**
 * Created by MYPC on 8/1/2016.
 */
public class ConvertMapToCSVTest {
    public static void main(String[] args) throws IOException {

        List<HashMap<String, String>> myArrList = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> map;

        /*** Rows 1 ***/
        map = new HashMap<String, String>();
        map.put("CustomerID", "C001");
        map.put("Name", "Ajay Kumar");
        map.put("Email", "ajay@gmail.com");
        map.put("CountryCode", "TH");
        map.put("Budget", "1000000");
        map.put("Used", "600000");
        myArrList.add(map);

        /*** Rows 2 ***/
        map = new HashMap<String, String>();
        map.put("CustomerID", "C002");
        map.put("Name", "Rahul Kumar");
        map.put("Email", "Rahul.kumar@gmail.com");
        map.put("CountryCode", "UK");
        map.put("Budget", "2000000");
        map.put("Used", "800000");
        myArrList.add(map);

        /*** Rows 3 ***/
        map = new HashMap<String, String>();
        map.put("CustomerID", "C003");
        map.put("Name", "Wasim Akram");
        map.put("Email", "waism.atnet@rediff.com");
        map.put("CountryCode", "US");
        map.put("Budget", "3000000");
        map.put("Used", "600000");
        myArrList.add(map);

        /*** Rows 4 ***/
        map = new HashMap<String, String>();
        map.put("CustomerID", "C004");
        map.put("Name", "Santosh Kumar");
        map.put("Email", "santosh.ku@yahoo.com");
        map.put("CountryCode", "US");
        map.put("Budget", "4000000");
        map.put("Used", "100000");
        myArrList.add(map);

        File file = new File("d:\\sample.csv");
        // Create a File and append if it already exists.
        Writer writer = new FileWriter(file, true);
        Reader reader = new FileReader(file);
        //Copy List of Map Object into CSV format at specified File location.
        csvWriter(myArrList, writer);
        //Read CSV format from specified File location and print on console..
        csvReader(reader);
    }

    /**
     * @param listOfMap
     * @param writer
     * @throws IOException
     */
    public static void csvWriter(List<HashMap<String, String>> listOfMap, Writer writer) throws IOException {
        CsvSchema schema = null;
        CsvSchema.Builder schemaBuilder = CsvSchema.builder();
        if (listOfMap != null && !listOfMap.isEmpty()) {
            for (String col : listOfMap.get(0).keySet()) {
                schemaBuilder.addColumn(col);
            }
            schema = schemaBuilder.build().withLineSeparator("\r").withHeader();
        }
        CsvMapper mapper = new CsvMapper();
        mapper.writer(schema).writeValues(writer).writeAll(listOfMap);
        writer.flush();
    }

    /**
     * 
     * @param collection
     * @param writer
     * @param 
     * @throws IOException
     */
    public static  void csvWriter(Collection collection, Writer writer) throws IOException {
        if (collection != null && collection.size() > 0) {
            CsvMapper mapper = new CsvMapper();
            Object[] objects = collection.toArray();
            Class type = objects[0].getClass();
            CsvSchema schema = mapper.schemaFor(type).withHeader();
            mapper.writer(schema).writeValues(writer).write(objects);
        } else {
            writer.write("No Data");
        }
        writer.flush();
    }


    /**
     * @param reader
     * @throws IOException
     */

    public static void csvReader(Reader reader) throws IOException {
        Iterator<Map<String, String>> iterator = new CsvMapper()
                .readerFor(Map.class)
                .with(CsvSchema.emptySchema().withHeader())
                .readValues(reader);
        while (iterator.hasNext()) {
            Map<String, String> keyVals = iterator.next();
            System.out.println(keyVals);
        }
    }
}


A CSV file is created at specified location i.e d:\\sample.csv in file system.

Email,Used,Budget,CustomerID,CountryCode,Name
ajay@gmail.com,600000,1000000,C001,TH,"Ajay Kumar"
Rahul.kumar@gmail.com,800000,2000000,C002,UK,"Rahul Kumar"
waism.atnet@rediff.com,600000,3000000,C003,US,"Wasim Akram"
santosh.ku@yahoo.com,100000,4000000,C004,US,"Santosh Kumar"

Reading sample.csv file from file system.

{Email=ajay@gmail.com, Used=600000, Budget=1000000, CustomerID=C001, CountryCode=TH, Name=Ajay Kumar}
{Email=Rahul.kumar@gmail.com, Used=800000, Budget=2000000, CustomerID=C002, CountryCode=UK, Name=Rahul Kumar}
{Email=waism.atnet@rediff.com, Used=600000, Budget=3000000, CustomerID=C003, CountryCode=US, Name=Wasim Akram}
{Email=santosh.ku@yahoo.com, Used=100000, Budget=4000000, CustomerID=C004, CountryCode=US, Name=Santosh Kumar}

Hoping, It would be helpful !! Thanks

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s