CSV File Write Line By Line

CSV File Write Line By Line

In the post I am going to explaining CSV file write line by line by using opencsv jar file. You can see what is CSV file?. Before going to write java program we need to download opencsv jar file.

OpenCsvWriter.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.narayanatutorial.opencsv;

import au.com.bytecode.opencsv.CSVWriter;
import java.io.FileWriter;

public class OpenCsvWriter {

    public static void main(String args[]) {
                String csvFilename = "D:/narayanatutorial/SampleFiles/OpenCSVWrite.csv";
        try {
            
            CSVWriter writer = new CSVWriter(new FileWriter(csvFilename));
            String[] profile = "Narayana,Ragi,'12345678901234569870,''".split(",");
            String[] header="FIRSTNAME,LASTNAME,AGE".split(",");
            writer.writeNext(header);
            writer.writeNext(profile);
            writer.close();
            System.out.println("CSV file created succesfully.");
        } catch (Exception e) {
            System.out.println("exception :" + e.getMessage());
        }

    }
}

Output

CSV file created succesfully.

You can open the csv file in the notepad and see the following output.

"FIRSTNAME","LASTNAME","AGE"
"Narayana","Ragi","'12345678901234569870","''"

you can find the above sample program in the github. If you have git account you can download from github and other sample programs also available and find the below github link to download. We used Netbeans IDE to develop sample programs. So you can directly import into Netbeans if you are having Netbeans else create sample project in your IDE and replace src folder.

Git link

I hope you understand CSV File Write Line By Line by using opencsv jar file.

Leave a Reply