DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • 7 Tips on Writing Good Technical Content
  • High-Performance Java Serialization to Different Formats
  • Did You Know the Fastest Way of Serializing a Java Field Is Not Serializing It at All?
  • Open-Source SPL That Can Execute SQL Without RDB

Trending

  • HTTP QUERY Method Explained: RFC 10008, Ecosystem Adoption, and a Quarkus Implementation
  • The Tectonic AI Platform: A Framework for Taming App Sprawl and Data Fragmentation
  • Engineering Production Agentic Systems: Part 3: The Topology
  • The Retry Budget Pattern: How to Stop Retry Storms in API-Led and Microservice Systems

CSV Operations using OpenCSV

By 
Veeresham Kardas user avatar
Veeresham Kardas
·
Dec. 10, 14 · Tutorial
Likes (0)
Comment
Save
Tweet
Share
29.2K Views

Join the DZone community and get the full member experience.

Join For Free

OpenCSV is one of the best tools for CSV operations. We will see how to use OpenCSV for basic reading and writing operations.

How to Use

The Maven dependency for OpenCSV is as follows:

     <dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>2.3</version>
     </dependency>

What it provides

  • CSVReader: Provides the operations to read the CSV file as a list of String array. It can used along with CsvToBean to read the data as list of beans
  • CSVWriter: Allows us to write the data to a CSV file.
  • CsvToBean: Reads the CSV data and coverts to a bean using MappingStrategy.
  • MappingStrategy: It's an interface to define the mapping between the data being written to the header of the CSV. It's been implemented by HeaderColumnNameMappingStrategy,  ColumnPositionMappingStrategy and HeaderColumnNameTranslateMappingStrategy for respective mapping formats. 

Writing to a CSV file

See below an example of writing a CSV file using CSVWriter

        String csv = "/tmp/employee.csv";
        CSVWriter writer = new CSVWriter(new FileWriter(csv));

        String[] header= new String[]{"Name","Age","Salary","Address"};
        writer.writeNext(header);

        List<String[]> allData = new ArrayList<String[]>();
        for(int i=0;i<3;i++)
        {
            String[] data = new String[]{"Blogger"+i,"20"+i,"20.0002",i+" World Wide Web"};
            allData.add(data);
        }

        writer.writeAll(allData);
        writer.close();

Points to be noted

  • CSVWriter can write line by line using writeNext
  • writeAll can used to write full CSV data at once.
  • By default, the separator will be a comma(,). If you want to make another character as a separator we can pass it as an argument.
  • The maximum possible signature of the constructor is :
    public CSVWriter(Writer writer, char separator, char quotechar, char escapechar)

Output

"Name","Age","Salary","Address"
"Blogger0","200","20.0002","0 World Wide Web"
"Blogger1","201","20.0002","1 World Wide Web"
"Blogger2","202","20.0002","2 World Wide Web"

Reading from a CSV File

Reading a csv can be done in two ways. One as a list of string array or as a bean.

Reading as an array

        CSVReader csvReader = new CSVReader(new FileReader("/tmp/employee.csv"));
        List<String[]> allData = csvReader.readAll();

        for(String[] data : allData)
        {
            for(String s : data)
            {
                System.out.print(s+";");
            }
            System.out.println();
        }

        csvReader.close();

Points to be noted

  • As CSVWriter, CSVReader also provides readNext and readAll methods to read one line or full data respectively and the delimiter can be specified while reading the file (Other than comma(,)). 
  • Adding to that, we can set the ignore spaces, default skip lines, special quote character etc.. while reading a CSV file
  • When we read as an array of string, header will not ignored. So we need to skip the first element in the list or we can specify start line while creating CSVReader. See the output below

Output

Name;Age;Salary;Address;
Blogger0;200;20.0002;0 World Wide Web;
Blogger1;201;20.0002;1 World Wide Web;
Blogger2;202;20.0002;2 World Wide Web;

Reading as a Bean

The CSV data can be read into a bean, but we need to define the mapping strategy and pass the strategy to CsvToBean to parse the data into a bean.

        Map<String, String> mapping = new HashMap<String, String>();
        mapping.put("Name", "name");
        mapping.put("Age", "age");
        mapping.put("Salary", "salary");
        mapping.put("address", "Address");

        HeaderColumnNameTranslateMappingStrategy<Employee> strategy = new HeaderColumnNameTranslateMappingStrategy<Employee>();
        strategy.setType(Employee.class);
        strategy.setColumnMapping(mapping);

        CSVReader csvReader = new CSVReader(new FileReader("/tmp/employee.csv"));
        CsvToBean<Employee> csvToBean = new CsvToBean<Employee>();
        List<Employee> list = csvToBean.parse(strategy, csvReader);

        for(Employee e : list)
        {
            System.out.println(e);
        }

Points to be noted 

  • Here we used HeaderColumnNameTranslateMappingStrategy which maps the column id to the bean property. 
  • CSV Reader and strategy to be passed to CsvToBean to read the data into the bean. When we parse, we get the list of bean as a result.

Output

Name : Blogger0; Age : 200; Salary : 20.0002; Addresss : 0 World Wide Web
Name : Blogger1; Age : 201; Salary : 20.0002; Addresss : 1 World Wide Web
Name : Blogger2; Age : 202; Salary : 20.0002; Addresss : 2 World Wide Web

See more at my blog 

Happy Learning!!!!

file IO

Opinions expressed by DZone contributors are their own.

Related

  • 7 Tips on Writing Good Technical Content
  • High-Performance Java Serialization to Different Formats
  • Did You Know the Fastest Way of Serializing a Java Field Is Not Serializing It at All?
  • Open-Source SPL That Can Execute SQL Without RDB

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook