Saturday, November 23, 2024
Google search engine
HomeLanguagesJavaWriting a CSV file in Java using OpenCSV

Writing a CSV file in Java using OpenCSV

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

    Dominic Rubhabha-Wardslaus
    Dominic Rubhabha-Wardslaushttp://wardslaus.com
    infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
    RELATED ARTICLES

    Most Popular

    Recent Comments