Writing Data Into CSV File Using Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to write data to CSV (Comma-Separated Values) files using Java. CSV files are a common format for storing tabular data and are widely used for data exchange between different applications.

You will use the OpenCSV library, which provides simple methods to write and read CSV files in Java. By the end of this lab, you will have created a Java program that can write data to a new CSV file and append additional data to an existing file.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java(("Java")) -.-> java/FileandIOManagementGroup(["File and I/O Management"]) java/BasicSyntaxGroup -.-> java/output("Output") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("Packages / API") java/FileandIOManagementGroup -.-> java/files("Files") java/FileandIOManagementGroup -.-> java/create_write_files("Create/Write Files") java/FileandIOManagementGroup -.-> java/io("IO") subgraph Lab Skills java/output -.-> lab-117458{{"Writing Data Into CSV File Using Java"}} java/packages_api -.-> lab-117458{{"Writing Data Into CSV File Using Java"}} java/files -.-> lab-117458{{"Writing Data Into CSV File Using Java"}} java/create_write_files -.-> lab-117458{{"Writing Data Into CSV File Using Java"}} java/io -.-> lab-117458{{"Writing Data Into CSV File Using Java"}} end

Understanding CSV Files and Setting Up the Project

CSV (Comma-Separated Values) is a simple file format used to store tabular data. Each line in a CSV file represents a row of data, and the values within a row are separated by commas. For example, a CSV file containing student data might look like this:

Name,Age,Email
John Doe,25,[email protected]
Jane Smith,22,[email protected]

Let's start by creating a simple Maven project to work with CSV files. Maven is a build automation tool that will help us manage the dependencies for our project.

  1. First, open the terminal in WebIDE and navigate to the project directory:
cd ~/project/csv-writer
  1. Create a new file named pom.xml in the project directory. This file will define our project structure and dependencies:
touch pom.xml
  1. Open the pom.xml file in the WebIDE editor and add the following content:
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>csv-writer</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>5.4</version>
        </dependency>
    </dependencies>
</project>

This XML file defines our project and adds the OpenCSV library (version 5.4) as a dependency. OpenCSV provides simple classes for reading and writing CSV files.

  1. Create the directory structure for our Java source code:
mkdir -p src/main/java/com/example

This command creates the standard Maven directory structure for Java source code.

Creating a Simple CSV Writer Program

Now that we have set up our project with the OpenCSV dependency, we can create a Java program that writes data to a CSV file.

  1. Create a new Java class file named CSVWriterExample.java in the directory structure we created earlier:
touch src/main/java/com/example/CSVWriterExample.java
  1. Open CSVWriterExample.java in the WebIDE editor and add the following code:
package com.example;

import com.opencsv.CSVWriter;
import java.io.FileWriter;
import java.io.IOException;

public class CSVWriterExample {
    public static void main(String[] args) {
        try {
            // Create a new CSVWriter instance
            // The first parameter is a FileWriter with the file path
            // The second parameter is the separator character (default is comma)
            // The third parameter is the quote character (default is double quote)
            // The fourth parameter is the escape character (default is backslash)
            // The fifth parameter is the line ending (default is newline)
            CSVWriter writer = new CSVWriter(new FileWriter("students.csv"),
                                           CSVWriter.DEFAULT_SEPARATOR,
                                           CSVWriter.DEFAULT_QUOTE_CHARACTER,
                                           CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                                           CSVWriter.DEFAULT_LINE_END);

            // Write header line
            String[] header = {"Name", "Age", "Email"};
            writer.writeNext(header);

            // Write data lines
            String[] student1 = {"John Doe", "25", "[email protected]"};
            writer.writeNext(student1);

            String[] student2 = {"Jane Smith", "22", "[email protected]"};
            writer.writeNext(student2);

            // Close the writer to flush and release resources
            writer.close();

            System.out.println("CSV file created successfully!");

        } catch (IOException e) {
            System.out.println("Error writing to CSV file: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

This code does the following:

  • Imports the necessary classes from the OpenCSV library and Java I/O package
  • Creates a CSVWriter object that will write to a file named students.csv
  • Writes a header row with field names
  • Writes two rows of student data
  • Closes the writer to ensure all data is flushed to the file

The CSVWriter constructor has five parameters:

  • FileWriter: Specifies the file to write to
  • Separator character: The character used to separate fields (default is comma)
  • Quote character: The character used to quote fields (default is double quote)
  • Escape character: The character used to escape special characters (default is backslash)
  • Line ending: The character used to end lines (default is newline)
  1. Compile the Java program using Maven:
cd ~/project/csv-writer
mvn compile

This command compiles our Java source code using the Maven build system.

Running the CSV Writer Program

Let's run our Java program to create the CSV file and see the results.

  1. Execute the compiled Java program using Maven:
cd ~/project/csv-writer
mvn exec:java -Dexec.mainClass="com.example.CSVWriterExample"

If you see an error message about the exec-maven-plugin, we need to add it to our pom.xml:

  1. Open pom.xml in the WebIDE editor and update it to include the exec-maven-plugin:
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>csv-writer</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>5.4</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <mainClass>com.example.CSVWriterExample</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
  1. Now run the program again:
mvn exec:java

You should see the message "CSV file created successfully!" in the terminal output.

  1. Let's verify that our CSV file was created and contains the expected data:
cat students.csv

The output should show the CSV file content, which will be something like:

"Name","Age","Email"
"John Doe","25","[email protected]"
"Jane Smith","22","[email protected]"

Notice that the output includes quote characters around each field. This is the default behavior of OpenCSV, which helps handle fields that contain special characters like commas.

Appending Data to an Existing CSV File

Now that we've created a CSV file, let's modify our Java program to append additional data to the existing file rather than overwriting it.

  1. Create a new Java file named CSVAppendExample.java:
touch src/main/java/com/example/CSVAppendExample.java
  1. Open CSVAppendExample.java in the WebIDE editor and add the following code:
package com.example;

import com.opencsv.CSVWriter;
import java.io.FileWriter;
import java.io.IOException;

public class CSVAppendExample {
    public static void main(String[] args) {
        try {
            // Create a CSVWriter in append mode by setting the second parameter of FileWriter to true
            CSVWriter writer = new CSVWriter(new FileWriter("students.csv", true));

            // Write additional data to the existing file
            String[] student3 = {"Robert Johnson", "24", "[email protected]"};
            writer.writeNext(student3);

            String[] student4 = {"Maria Garcia", "23", "[email protected]"};
            writer.writeNext(student4);

            // Close the writer
            writer.close();

            System.out.println("Data appended to CSV file successfully!");

        } catch (IOException e) {
            System.out.println("Error appending to CSV file: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

This code is similar to our previous example, but with two important differences:

  • We create the FileWriter with a second parameter set to true, which puts it in append mode
  • We don't write a header row, since the file already has one
  1. Run the program to append data to our existing CSV file:
cd ~/project/csv-writer
mvn exec:java -Dexec.mainClass="com.example.CSVAppendExample"
  1. Let's check the content of our CSV file now:
cat students.csv

You should see the original data plus the newly appended records:

"Name","Age","Email"
"John Doe","25","[email protected]"
"Jane Smith","22","[email protected]"
"Robert Johnson","24","[email protected]"
"Maria Garcia","23","[email protected]"

As you can see, the new data was added to the end of the file without disturbing the existing content.

  1. Let's create one more example that demonstrates writing CSV files with custom separators:
touch src/main/java/com/example/CSVCustomExample.java
  1. Open CSVCustomExample.java in the WebIDE editor and add the following code:
package com.example;

import com.opencsv.CSVWriter;
import java.io.FileWriter;
import java.io.IOException;

public class CSVCustomExample {
    public static void main(String[] args) {
        try {
            // Create a CSVWriter with semicolon as separator instead of comma
            CSVWriter writer = new CSVWriter(new FileWriter("students_semicolon.csv"),
                                           ';',
                                           CSVWriter.DEFAULT_QUOTE_CHARACTER,
                                           CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                                           CSVWriter.DEFAULT_LINE_END);

            // Write header line
            String[] header = {"Name", "Age", "Email"};
            writer.writeNext(header);

            // Write data lines
            String[] student1 = {"John Doe", "25", "[email protected]"};
            writer.writeNext(student1);

            String[] student2 = {"Jane Smith", "22", "[email protected]"};
            writer.writeNext(student2);

            // Close the writer
            writer.close();

            System.out.println("CSV file with semicolon separator created successfully!");

        } catch (IOException e) {
            System.out.println("Error writing to CSV file: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

This example creates a CSV file using semicolons as separators instead of commas, which is common in some European countries where commas are used as decimal separators.

  1. Run the custom separator example:
cd ~/project/csv-writer
mvn exec:java -Dexec.mainClass="com.example.CSVCustomExample"
  1. Check the content of the new CSV file:
cat students_semicolon.csv

You should see the CSV file with semicolons as separators:

"Name";"Age";"Email"
"John Doe";"25";"[email protected]"
"Jane Smith";"22";"[email protected]"

Summary

In this lab, you learned how to write data to CSV files using Java with the OpenCSV library. You successfully:

  1. Set up a Java project with the OpenCSV dependency
  2. Created a basic Java program to write data to a new CSV file
  3. Modified the program to append data to an existing CSV file
  4. Created a custom CSV writer with a different separator character

These skills are useful for many applications, such as data export, report generation, and data exchange between systems. CSV is a widely used format due to its simplicity and compatibility with spreadsheet software and data analysis tools.

Some key takeaways:

  • The CSVWriter class from OpenCSV provides an easy way to write CSV files in Java
  • To create a new CSV file, use new FileWriter(filename) with the CSVWriter
  • To append to an existing CSV file, use new FileWriter(filename, true) with the CSVWriter
  • Always close the writer using writer.close() to ensure all data is written to the file
  • You can customize the separator, quote character, and other aspects of the CSV format

With these basics, you should be able to incorporate CSV writing capabilities into your Java applications.