Print

Write Csv File In Java

Using Java CSV package, we can read/write a csv file. In this example, we learn how to write a csv file. You create a maven-based java project and add the following dependency in the pom.xml file. 

 

<dependency>
        <groupId>net.sourceforge.javacsv</groupId>
        <artifactId>javacsv</artifactId>
        <version>2.0</version>
</dependency>

In this example, we write a "writetest.csv" file with the following content

TestId,TestName,TestModule,TestType,TestSteps,Action,TestResult,Note
1234,Login,Dashboard,Smoke,1,Open Browser,Pass,Browser opened

Write the following code in the "WriteCsvFile.java" class

package com.example.csv;
import com.csvreader.CsvWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteCsvFile {

    public static void main(String[] args) {
        //define output file name
        String csvOutputFile = "writetest.csv";
        //check if file exist
        boolean isFileExist = new File(csvOutputFile).exists();
            try {
                //create a FileWriter constructor to open a file in appending mode
                CsvWriter testcases = new CsvWriter(new FileWriter(csvOutputFile, true), ',');
                //write header column if the file did not already exist
                if(!isFileExist)
                {
                    testcases.write("TestId");
                    testcases.write("TestName");
                    testcases.write("TestModule");
                    testcases.write("TestType");
                    testcases.write("TestSteps");
                    testcases.write("Action");
                    testcases.write("TestResult");
                    testcases.write("Note");
                    //end the record
                    testcases.endRecord();
                }
             //add record to the file
                testcases.write("1234");
                testcases.write("Login");
                testcases.write("Dashboard");
                testcases.write("Smoke");
                testcases.write("1");
                testcases.write("Open Browser");
                testcases.write("Pass");
                testcases.write("Browser opened");
                //end the record
                testcases.endRecord();
                //close the file
                testcases.close();

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

        }
    }

Run the code above and open the "writetest.csv" file. You will see the content below.

TestId,TestName,TestModule,TestType,TestSteps,Action,TestResult,Note
1234,Login,Dashboard,Smoke,1,Open Browser,Pass,Browser opened