Friday, August 14, 2009

Java : Generate CSV File

This is simple program to generate CSV file. As we know csv is nothing but comma separated values, so we will write file with '.csv' extension.


/* GenerateCSVFile.java*/

import java.io.*;

public class GenerateCSVFile
{
public static void main(String[] args)
{
//name of the file, it takes default path ie. current directory
//you can also provide absolute/relative path
String CSVFileToWrite = "MyCSVFile.csv";//file with .csv extension

try
{
File file=new File(CSVFileToWrite);
FileWriter fw =new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);

for(int line = 0 ; line < 10 ; line ++)
{
bw.write("A"+line+",B"+line+",C"+line);//writing comma separated values
bw.newLine();
bw.flush();//flushing
}

bw.close();//closing BufferedWriter

System.out.println("File generated sucessfully : "+file.getAbsolutePath());

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

}
}

1 comment:

  1. Very helpfull.

    Thank you very much.

    ReplyDelete