Writing text to a CSV file in Java using PrintWriter

A CSV(Comma Separated Value) file contains records in tabular format where the fields are separated by comma.

CSV is a common data exchange format and is frequently used to send data from one system to another system.

In this example, we will see how to create a CSV file in Java and write data into it.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class ExportToCSV {

  public static void main(String[] args) {
    PrintWriter pw;
    try {
      pw = new PrintWriter(new File("test.csv"));

      StringBuffer csvHeader = new StringBuffer("");
      StringBuffer csvData = new StringBuffer("");
      csvHeader.append("Name,Age,Designation\n");

      // write header
      pw.write(csvHeader.toString());

      // write data
      csvData.append("John");
      csvData.append(',');
      csvData.append("21");
      csvData.append(',');
      csvData.append("Engineer");
      csvData.append('\n');
      csvData.append("Mary");
      csvData.append(',');
      csvData.append("31");
      csvData.append(',');
      csvData.append("Manager");
      csvData.append('\n');
      pw.write(csvData.toString());
      pw.close();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

}

Output :

create csv file in java

© 2017 – 2023, https:. All rights reserved. On republishing this post, you must provide link to original post

2 comments

  1. Thanks for the solution

  2. I tried above code in my pragram but when data is greater then the size of the cell it is showing ##### instead of actual data in second column, i think it is because of the size on the cells or the alignment. But i didn’t find any solution to this issue. Please suggest something.

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: