The Wayback Machine - https://web.archive.org/web/20240616051725/https://www.geeksforgeeks.org/writing-a-csv-file-in-java-using-opencsv/
Open In App

Writing a CSV file in Java using OpenCSV

Last Updated : 07 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in a column by column, and split it by a separator (e.g normally it is a comma “, ”).

OpenCSV is a CSV parser library for Java. OpenCSV supports all the basic CSV-type operations you are want to do. Java 7 is currently the minimum supported version for OpenCSV. Java language does not provide any native support for effectively handling CSV files so we are using OpenCSV for handling CSV files in Java.

How to add OpenCSV in your Project?

  • For maven project, you can include the OpenCSV maven dependency in pom.xml file.




    <dependency>
        <groupId>com.opencsv</groupId>
        <artifactId>opencsv</artifactId>
        <version>4.1</version>
    </dependency>

    
    

  • For Gradle Project, you can include the OpenCSV dependency.

    compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
  • You can Download OpenCSV Jar and include in your project class path.
  • Writing a CSV File

      Writing a CSV file is as simple as reading. Create an instance of CSVWriter by passing FileWriter object as parameter and start writing data to CSV file using methods of CSVWriter Class. After writing data we need to close CSVWriter connection by calling close() method of CSVWriter class.

    1. Write Data Line by line – CSVWriter can write line by line using writeNext() method where a string array is passed with each comma-separated element as a separate entry.
      CODE:




      public static void writeDataLineByLine(String filePath)
      {
          // first create file object for file placed at location
          // specified by filepath
          File file = new File(filePath);
          try {
              // create FileWriter object with file as parameter
              FileWriter outputfile = new FileWriter(file);
        
              // create CSVWriter object filewriter object as parameter
              CSVWriter writer = new CSVWriter(outputfile);
        
              // adding header to csv
              String[] header = { "Name", "Class", "Marks" };
              writer.writeNext(header);
        
              // add data to csv
              String[] data1 = { "Aman", "10", "620" };
              writer.writeNext(data1);
              String[] data2 = { "Suraj", "10", "630" };
              writer.writeNext(data2);
        
              // closing writer connection
              writer.close();
          }
          catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      }

      
      

      Output: result.csv file with following Data

      "Name", "Class", "Marks"
      "Aman", "10", "620"
      "Suraj", "10", "630"
      
    2. Write all Data at once- For witting data at once call writeAll() method of CSVWriter class and pass A List of String[] as the parameter with each String[] representing a line of the file.
      CODE:




      public static void writeDataAtOnce(String filePath)
      {
        
          // first create file object for file placed at location
          // specified by filepath
          File file = new File(filePath);
        
          try {
              // create FileWriter object with file as parameter
              FileWriter outputfile = new FileWriter(file);
        
              // create CSVWriter object filewriter object as parameter
              CSVWriter writer = new CSVWriter(outputfile);
        
              // create a List which contains String array
              List<String[]> data = new ArrayList<String[]>();
              data.add(new String[] { "Name", "Class", "Marks" });
              data.add(new String[] { "Aman", "10", "620" });
              data.add(new String[] { "Suraj", "10", "630" });
              writer.writeAll(data);
        
              // closing writer connection
              writer.close();
          }
          catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      }

      
      

      Output: result.csv file with following Data

      "Name", "Class", "Marks"
      "Aman", "10", "620"
      "Suraj", "10", "630"
      

    Writing CSV File with different separator

    By default, the separator for CSV will be a comma(, ). If you want to make another character as a separator so it can be passed as an argument to CSVWriter class.

    Syntax :
    CSVWriter(Writer writer, char separator, char quotechar,
                                  char escapechar, String lineEnd)
    Description : Constructs CSVWriter with supplied separator,
    quote char, escape char and line ending.
    

    Code:




    public static void writeDataForCustomSeparatorCSV(String filePath)
    {
      
        // first create file object for file placed at location
        // specified by filepath
        File file = new File(filePath);
      
        try {
            // create FileWriter object with file as parameter
            FileWriter outputfile = new FileWriter(file);
      
            // create CSVWriter with '|' as separator
            CSVWriter writer = new CSVWriter(outputfile, '|',
                                             CSVWriter.NO_QUOTE_CHARACTER,
                                             CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                                             CSVWriter.DEFAULT_LINE_END);
      
            // create a List which contains String array
            List<String[]> data = new ArrayList<String[]>();
            data.add(new String[] { "Name", "Class", "Marks" });
            data.add(new String[] { "Aman", "10", "620" });
            data.add(new String[] { "Suraj", "10", "630" });
            writer.writeAll(data);
      
            // closing writer connection
            writer.close();
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    
    

    Output: result.csv file with following Data

    Name|Class|Marks
    Aman|10|620
    Suraj|10|630
    

    Example:
    Let’s create java program which generate a semi-colon separated csv file and contains the data provided as input.

    Input:
    Enter no of rows
    9
    Enter Data
    Name Class Marks
    Aman 10 543
    Amar 10 541
    Sanjeet 10 555
    Luv 10 580
    Ranjeet 10 512
    Rabi 10 540
    Dev 10 333
    Sunny 10 198
    

    Code:




    // Java program to illustrate
    // for Writing Data in CSV file
    import java.io.*;
    import java.util.*;
    import com.opencsv.CSVWriter;
      
    public class ResultGenerator {
        private static final String CSV_FILE_PATH
            = "./result.csv";
        public static void main(String[] args)
        {
            addDataToCSV(CSV_FILE_PATH);
        }
        public static void addDataToCSV(String output)
        {
            // first create file object for file placed at location
            // specified by filepath
            File file = new File(output);
            Scanner sc = new Scanner(System.in);
            try {
                // create FileWriter object with file as parameter
                FileWriter outputfile = new FileWriter(file);
      
                // create CSVWriter with ';' as separator
                CSVWriter writer = new CSVWriter(outputfile, ';',
                                                 CSVWriter.NO_QUOTE_CHARACTER,
                                                 CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                                                 CSVWriter.DEFAULT_LINE_END);
      
                // create a List which contains Data
                List<String[]> data = new ArrayList<String[]>();
      
                System.out.println("Enter no of rows");
                int noOfRow = Integer.parseInt(sc.nextLine());
                System.out.println("Enter Data");
                for (int i = 0; i < noOfRow; i++) {
                    String row = sc.nextLine();
                    String[] rowdata = row.split(" ");
                    data.add(rowdata);
                }
      
                writer.writeAll(data);
      
                // closing writer connection
                writer.close();
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    
    

    Output: result.csv file with following Data

    Name;Class;Marks
    Aman;10;543
    Amar;10;541
    Sanjeet;10;555
    Luv;10;580
    Ranjeet;10;512
    Rabi;10;540
    Dev;10;333
    Sunny;10;198
    
    

    In future articles, we will include more Operations on CSV file using OpenCSV.
    Reference:OpenCSV Documentation, CSVWriter class documentation



    Similar Reads

    Reading a CSV file in Java using OpenCSV
    A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in column by column, and split it by a separator (e.g normally it is a comma “, ”). OpenCSV is a CSV parser library for Java. OpenCSV supports all the basic CSV-type operations you are want to do. Java 7 is currently the minimum supported version for OpenCSV. Java lang
    7 min read
    Mapping Java Beans to CSV Using OpenCSV
    The need to convert Java Beans(Objects) to CSV file arises very commonly and there are many ways to write Bean into CSV file but one of the best ways to map java bean to CSV is by using OpenCSV Library. In OpenCSV there is a class name StatefulBeanToCsvBuilder which helps to convert Java Beans to CSV. The first task is to add the OpenCSV library in
    4 min read
    Mapping CSV to JavaBeans Using OpenCSV
    OpenCSV provides classes to map CSV file to a list of Java-beans. CsvToBean class is used to map CSV data to JavaBeans. The CSV data can be parsed to a bean, but what is required to be done is to define the mapping strategy and pass the strategy to CsvToBean to parse the data into a bean. HeaderColumnNameTranslateMappingStrategy is the mapping stra
    4 min read
    CSV File Format | .csv Extension
    What are CSV Files?The full form of CSV is Comma-separated values. Comma-separated value is a simple yet powerful file format to store and exchange data. Values are separated using commas in this plain text file format. CSV files are often used to store data in a tabular format, such as spreadsheets or databases. These files are easy to create and
    3 min read
    How to Write JSON Array to CSV File using Java?
    We will see how to read a JSONArray from a JSON file and write the contents to a CSV file using Java. JavaScript Object Notation (JSON) is a standard text-based format for representing structured data that is based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to
    3 min read
    How to Extract Email Addresses, Phone Numbers from a CSV File using Java?
    CSV stands for Comma Separated Values. A CSV file is a plain text file. CSV file is used to store the records. CSV File records are stored with delimiter separator value. Problem Statement A CSV file is given. The task is to read and extract phone numbers, and email ids from the given CSV file, and return the list of phone numbers and emails as out
    2 min read
    Reading and Writing Data to Excel File in Java using Apache POI
    In Java, reading an Excel file is not similar to reading a Word file because of cells in an Excel file. JDK does not provide a direct API to read data from Excel files for which we have to toggle to a third-party library that is Apache POI. Apache POI is an open-source java library designed for reading and writing Microsoft documents in order to cr
    5 min read
    Reading and Writing Properties File in Java
    The property file is a file we use in the Java Programming language to keep the configuration parameters. These files we called Resource Bundle because it is a bundle of resources that we are going to use in the application. What are the configuration parameters? Configuration parameters are the parameters that you use at the time of configuring yo
    4 min read
    Writing List Contents to Text File After Deleting String in Java
    To write a List&lt;String&gt; to a text file after deleting a specific string, you can use the following steps: Iterate through the List&lt;String&gt; and use the remove() method to remove the desired string.Open a FileWriter and BufferedWriter to write to the text file.Iterate through the modified List&lt;String&gt; and write each element to the t
    3 min read
    How to convert CSV string file to a 2D array of objects using JavaScript ?
    A CSV is a comma-separated values file with a .csv extension, which allows data to be saved in a tabular format. In this article, we will learn to convert the data of a CSV string to a 2D array of objects, where the first row of the string is the title row using JavaScript. Given a comma-separated values (CSV) string to a 2D array, using Javascript
    4 min read
    Article Tags :
    Practice Tags :