Java: Writing data to a tab delimited file

Java: Writing data to a tab delimited file

I have included a simple Java function to print data to a tab delimited file with the extension csv for the convenience of opening the file with Microsoft Excel. I found this very helpful in my last project and hope it will help someone else :).


public void PrintDataToTabDelimitedFile()
{
try {
// Tab delimited file will be written to data with the name tab-file.csv
FileWriter fos = new FileWriter("data/tab-file.csv");
PrintWriter dos = new PrintWriter(fos);
dos.println("Heading1\tHeading2\tHeading3\t");
// loop through all your data and print it to the file
for (int i=0;i<endOfData;i++)
{
dos.print(value1+"\t");
dos.print(value2+"\t");
dos.print(value3+"\t");
dos.println();
}
dos.close();
fos.close();
} catch (IOException e) {
System.out.println("Error Printing Tab Delimited File");
}
}