Read and Write CSV files in Java



Introduction

        CSV(Comma-Separated Values) files are a common way to store structured data and Java offers various methods to efficiently read and write CSV files. Java does not provide any native support for effectively handling CSV files so in this article, we will focus on one of the most powerful and flexible approaches for handling CSV files; using the OpenCSV library.

 

OpenCSV is a versatile and powerful CSV parser library for Java. It supports a wide range of operations for reading and writing CSV files, making it a valuable tool for any Java developer. 

 

Getting Started with OpenCSV:

To begin using OpenCSV in your Java project, you have several options

 

1. Maven Dependency

For a Maven project, you can include the OpenCSV dependency in your pom.xml file as follows:

<dependency>

        <groupId>com.opencsv</groupId>

        <artifactId>opencsv</artifactId>

        <version>4.1</version>

</dependency>

 

2. Gradle Dependency

compile group: 'com.opencsv', name: 'opencsv', version: '4.1'

 

3. Manual Download

Alternatively, you can download the OpenCSV JAR file and include it in your project's classpath.

 

Key Classes in opencsv 

  1. CSVReader – The CSVReader class is a fundamental component in OpenCSV, essential for reading CSV data. While it doesn't directly accept a file path as input, it requires a Reader object that represents an open file or stream. You typically provide a Reader that is initialized with a file path when creating an instance of CSVReader.
  2. CSVWriter – Use the CSVWriter class to write data to a CSV file. It provides methods to create and write CSV content efficiently. Similar to CSVReader, you provide CSVWriter with a Writer object representing the output file or stream.
  3. CsvToBean – If you want to populate your Java beans from the content of a CSV file, the CsvToBean class is the perfect choice. It simplifies the process of mapping CSV data to Java objects.
  4. BeanToCsv – This class is helpful when you need to export data to a CSV file from your Java application. It facilitates the conversion of Java objects to CSV format.

 

Reading CSV File

 

Example

Here's a Java code example that demonstrates how to read and write CSV files using the OpenCSV library.

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

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

            // Path to the CSV file for reading
            String csvFileToRead = "data.csv";

            // Path to the CSV file for writing
            String csvFileToWrite = "output.csv";

            try {
                // Read data from the CSV file
                readCSV(csvFileToRead);

                // Write data to a new CSV file
                writeCSV(csvFileToWrite);

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

        // Method to read data from a CSV file
        private static void readCSV(String filePath) throws IOException {

            try (CSVReader csvReader = new CSVReader(new FileReader(filePath))) {
                // The CSVReader is initialized with a FileReader, which takes the file path as an argument.
                // This establishes a connection to the CSV file for reading.
                String[] nextRecord;
                while ((nextRecord = csvReader.readNext()) != null) {
                    for (String cell : nextRecord) {
                        System.out.print(cell + "\t");
                    }
                    System.out.println();
                }
            }
        }

        // Method to write data to a CSV file
        private static void writeCSV(String filePath) throws IOException {
            try (CSVWriter csvWriter = new CSVWriter(new FileWriter(filePath))) {
                // The CSVWriter is initialized with a FileWriter, which takes the file path as an argument.
                // This establishes a connection to the CSV file for writing.
                // The file path is where the new CSV file will be created or overwritten.
                String[] data1 = {"John", "Doe", "25"};
                String[] data2 = {"Jane", "Smith", "30"};

                csvWriter.writeNext(data1);
                csvWriter.writeNext(data2);
            }
        }
}

 

Explanation
  1. We import the necessary classes from the OpenCSV library to work with CSV files: CSVReader and CSVWriter.
  2. In the main method, we specify the paths for the CSV file to read (csvFileToRead) and the CSV file to write (csvFileToWrite).
  3. We have two methods: readCSV and writeCSV.
  • readCSV method reads data from the specified CSV file. It uses a CSVReader to read data line by line and print it to the console.
  • writeCSV method creates a CSVWriter to write data to a new CSV file. In this example, we create a list of data arrays (data1 and data2) and add them to the CSV file.
  1. Inside the main method, we call both the readCSV and writeCSV methods, specifying the file paths as parameters. This will read and display data from the input CSV file and write data to the output CSV file.

 

Output

Assuming the ‘data.csv’ file contains the following CSV data:

Name,Last Name,Age

John,Doe,25

Jane,Smith,30

 

The output for the provided code will be as follows:

Name    Last Name    Age    

John    Doe    25    

Jane    Smith    30

 Which will be stored in a newly created ‘output.csv’ file.



Thanks for feedback.



Read More....
Java Exception Handling
HashMap in Java
Java : HashSet and LinkedHashSet
Inner classes in Java
Java Collections Framework
Java Data Types and Variables - Declaration and Initialization