Monday, September 21, 2009

Java Code to write to CSV File


Hello guys, Java Code Online is back again with an important code. The code for today is for making a CSV (Comma Separated File) file. The operation to make a CSV file in Java is similar to the Java Code to write to a file. The difference between these two is that a comma is inserted within the text, where ever we want the columns in MS EXCEL to change to new column.

The beauty of the .csv file is that, when this file is opened in MS Excel, then all the values which are separated by comma, are displayed in a new column. This is required many times, if we want to send data to different columns. Even there is an option to switch rows while writing.

The Java Code displayed today, makes a .csv file at a particular location on your hard disk. You need to change the path, according to your requirements. The code writes some data to the .csv file. It generates 3 columns and 2 rows. You can modify it, according to your own requirements.

The Java Code is provided below:-

/////////////////////////////////////

/** The below Java Code writes
 * some data to a file in CSV
 * (Comma Separated Value) File
 */

package developer;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class MakeCSVFile {

    public static void main(String[] args) throws IOException {

        //Note the "\\" used in the path of the file
        //instead of "\", this is required to read
        //the path in the String format.
        FileWriter fw = new FileWriter("D:\\JavaCodeFile\\WriteTest.csv");
        PrintWriter pw = new PrintWriter(fw);
       
        //Write to file for the first row
        pw.print("Hello guys");
        pw.print(",");
        pw.print("Java Code Online is maing");
        pw.print(",");
        pw.println("a csv file and now a new line is going to come");
       
        //Write to file for the second row
        pw.print("Hey");
        pw.print(",");
        pw.print("It's a");
        pw.print(",");
        pw.print("New Line");
       
        //Flush the output to the file
        pw.flush();
       
        //Close the Print Writer
        pw.close();
       
        //Close the File Writer
        fw.close();       
    }
}

/////////////////////////////////////

The code when run on my system a produces a file called WriteTest.csv, when opened with MS EXCEL, the output is shown below:-




I hoe that the code was useful to all of you. Java Code Online is going to be back soon.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Post a Comment