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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert Excel and CSV Documents to HTML in Java
  • Datafaker 2.0
  • How to Convert CSV to XML in Java
  • How to Convert XLSX to CSV in Java

Trending

  • Unlocking the Benefits of a Private API in AWS API Gateway
  • Docker Base Images Demystified: A Practical Guide
  • AI Meets Vector Databases: Redefining Data Retrieval in the Age of Intelligence
  • The Modern Data Stack Is Overrated — Here’s What Works
  1. DZone
  2. Coding
  3. Java
  4. Working With CSV Files in Java Using Apache Commons CSV

Working With CSV Files in Java Using Apache Commons CSV

Need to read CSV files quickly and efficiently in your Java projects? Let's get Apache Commons CSV added to your setup and see it in action.

By 
Akshay Sharma user avatar
Akshay Sharma
·
Apr. 30, 18 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
56.4K Views

Join the DZone community and get the full member experience.

Join For Free

The Apache Commons CSV library is a Java library that can be used to read and write CSV files in a very simple and easy way. Another advantage is that this Java library is open source and freely available to use.

First, we need to add the library to your project.

To add it a Maven dependency, you just need to add this dependency to your pom.xml file:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.5</version>
</dependency>

 

Or, to add it as a Gradle dependency, you can just add this to your dependencies within the build.gradle file:

compile "org.apache.commons:commons-csv:1.5"

 

Let's start by generating a simple CSV file — student.csv — in the following program.

Our program to generate a simple CSV file:

import java.io.IOException;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

public class BasicCsvWriter {
    public static void main(String[] args) {
        try {

            //We have to create the CSVPrinter class object 
            Writer writer = Files.newBufferedWriter(Paths.get("student.csv"));
            CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader("Student Name", "Fees"));

            //Writing records in the generated CSV file
            csvPrinter.printRecord("Akshay Sharma", 1000);
            csvPrinter.printRecord("Rahul Gupta", 2000);
            csvPrinter.printRecord("Jay Karn", 3000);

            //Writing records in the form of a list
            csvPrinter.printRecord(Arrays.asList("Dev Bhatia", 4000));

            csvPrinter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


This program generates the student.csv file with the content as follows:

Student Name, Fees
Akshay Sharma,1000 
Rahul Gupta,2000
Jay Karn,3000
Dev Bhatia,4000

 

Let's now read the content of the generated CSV file using the following program:

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

public class BasicCsvReader {

    public static void main(String[] args) throws IOException {
        BufferedReader reader = Files.newBufferedReader(Paths.get("student.csv"));
        CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withHeader("Student Name", "Fees").withIgnoreHeaderCase().withTrim());

        for (CSVRecord csvRecord: csvParser) {

            // Accessing Values by Column Index
            String name = csvRecord.get(0);

            //Accessing the values by column header name
            String fees = csvRecord.get("fees");

            //Printing the record 
            System.out.println("Record Number - " + csvRecord.getRecordNumber());
            System.out.println("Name : " + name);
            System.out.println("Fees : " + fees);
            System.out.println("\n\n");
        }
    }
}

 

The output will be generated on the console as follows:

Record Number - 1
Name : Akshay Sharma
Fees : 1000

Record Number - 2
Name : Rahul Gupta
Fees : 2000

Record Number - 3
Name : Jay Karn
Fees : 3000

Record Number - 4
Name : Dev Bhatia
Fees : 4000

 

CSV Java (programming language)

Published at DZone with permission of Akshay Sharma. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert Excel and CSV Documents to HTML in Java
  • Datafaker 2.0
  • How to Convert CSV to XML in Java
  • How to Convert XLSX to CSV in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!