How to read CSV file in Java

Posted on

Jackson data format module for reading and writing CSV-encoded data, either as “raw” data (sequence of String arrays ) , or via data binding to/from Java Objects (POJOs).

To use this extension on Maven-based projects, use following dependency:

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

Read CSV file based on Java Class.

AS below schema Java Object have explicitly defined Order and properties type to ensured that reading or writing the data in given order.


package com.example.model;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;

import java.io.Serializable;
import java.math.BigDecimal;

/**
 * Created by MYPC on 7/18/2016.
 */
@JsonPropertyOrder(value = {"id", "amount", "currency"})
@JsonRootName("transaction")
public class Transaction implements Serializable {
    public enum Currency {
        INR, HKD, EUR, USD
    }
    @JsonProperty
    private String id;
    @JsonProperty
    @JsonFormat(shape = JsonFormat.Shape.NUMBER)
    private BigDecimal amount;
    @JsonProperty
    private Currency currency;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public double getAmount() {
        return amount.doubleValue();
    }
    public void setAmount(BigDecimal amount) {
        this.amount = amount;
    }
    public Currency getCurrency() {
        return currency;
    }
    public void setCurrency(Currency currency) {
        this.currency = currency;
    }
    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("Transaction{");
        sb.append("id='").append(id).append('\'');
        sb.append(", amount=").append(amount);
        sb.append(", currency=").append(currency);
        sb.append('}');
        return sb.toString();
    }
}


Trade.csv  file reside in project “/src/main/resources” folder.

id,amount,currency
"1001",10000045.999,"EUR"
"1002",17777045.999,"HKD"
"1003",10000045.999,"USD"
"1004",1234045.999,"EUR"
"1005",100875.999,"HKD"
"1006",165780045.999,"EUR"
"1007",32452345.999,"INR"
"1008",7777777.999,"EUR"

 

Reading CSV file to Java Object.


package com.example;

import com.example.model.Transaction;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

import java.io.IOException;
import java.util.List;
/**
 * Created by MYPC on 7/18/2016.
 */
public class JSONSchemaReaderApp {

    public static void main(String[] args) throws IOException {

        CsvMapper csvMapper = new CsvMapper();
        CsvSchema csvSchema = csvMapper.typedSchemaFor(Transaction.class).withHeader();
        List list = new CsvMapper().readerFor(Transaction.class)
                .with(csvSchema.withColumnSeparator(CsvSchema.DEFAULT_COLUMN_SEPARATOR))
                .readValues(JSONSchemaReaderApp.class.getClassLoader().getResource("trade.csv"))
                .readAll();
        for (int i = 0; i < list.size(); i++) {
            System.out.printf(" Transaction Row [%d] : %s \n", i + 1, list.get(i));
        }
    }
}


Output:-

Transaction Row [1] : Transaction{id='1001', amount=10000045.999, currency=EUR}
Transaction Row [2] : Transaction{id='1002', amount=17777045.999, currency=HKD}
Transaction Row [3] : Transaction{id='1003', amount=10000045.999, currency=USD}
Transaction Row [4] : Transaction{id='1004', amount=1234045.999, currency=EUR}
Transaction Row [5] : Transaction{id='1005', amount=100875.999, currency=HKD}
Transaction Row [6] : Transaction{id='1006', amount=165780045.999, currency=EUR}
Transaction Row [7] : Transaction{id='1007', amount=32452345.999, currency=INR}
Transaction Row [8] : Transaction{id='1008', amount=7777777.999, currency=EUR}

Reading CSV file into Map


public static void main(String[] args) throws IOException {
        CsvMapper csvMapper = new CsvMapper();

        CsvSchema csvSchema = csvMapper.typedSchemaFor(Map.class).withHeader();
        MappingIterator<Map<String, String>> it = csvMapper.readerFor(Map.class).with(csvSchema.withColumnSeparator(CsvSchema.DEFAULT_COLUMN_SEPARATOR))
                .readValues(JSONSchemaReaderApp.class.getClassLoader().getResource("trade.csv"));
        List<Map<String, String>> listOfMapSchema = it.readAll();

        for (Map<String, String> map : listOfMapSchema) {
            System.out.println(map);
        }

    }

output:-

{id=1001, amount=10000045.999, currency=EUR}
{id=1002, amount=17777045.999, currency=HKD}
{id=1003, amount=10000045.999, currency=USD}
{id=1004, amount=1234045.999, currency=EUR}
{id=1005, amount=100875.999, currency=HKD}
{id=1006, amount=165780045.999, currency=EUR}
{id=1007, amount=32452345.999, currency=INR}
{id=1008, amount=7777777.999, currency=EUR}

Advertisements

2 thoughts on “How to read CSV file in Java

    […] 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 […]

    Like

    […] 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 […]

    Like

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