How to Create CSV file in Java ?

CSV file means comma separated values. You can open and edit csv file in any text editor and also you can use MS Excel for the same.

Here we will use FileWriter with Automatic Resource Management to create CSV file. If you do not aware of these two in check below two articles.

How to write File in Java ?
Automatic Resource Management in Java

Create CSV File Using FileWriter with Automatic Resource Management.

package com.infybuzz.file;

import java.io.FileWriter;

public class CreateCsvFile {

 public static void main(String[] args) {
  
  StringBuilder stringBuilder = new StringBuilder();
  
  stringBuilder.append("Name").append(",").append("Website").append(",").append("Country").append("\n");
  
  stringBuilder.append("Raj").append(",").append("www.infybuzz.com").append(",").append("India").append("\n");
  
  stringBuilder.append("John").append(",").append("www.infybuzz.com").append(",").append("USA");
  
  try ( FileWriter fileWriter = new FileWriter("D:\\hello.csv") ) {
   
   fileWriter.write(stringBuilder.toString());
   
  } catch(Exception ex) {
   ex.printStackTrace();
  }
 }

}

Output



0 Comments