Custom Util: CSV File Writer

In many utilities or operations we want output to be in CSV file format. This is frequently used operation so it is always better to have util class which can handle all this CSV file writing.
Posting CSV file writer util class along with a test class. Please share your thoughts to optimize this code.

CSV File Writer:
package com.blogspot.maheshmhetre.util;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Util class used for CSV file writing.
 * @author mmhetre
 *
 */
public class CSVFileWriter {

 public static final String FILE_SEPARATOR = System.getProperty("file.separator");

 private StringBuilder outputStr = null;
 private FileWriter fw = null;
 
 private String csvFilePath = ""; 

 /**
  * Constructor.
  * @param filePathWithoutFileName CSV file path without file name
  * @param fileName File Name without file extension/type
  * @param shouldAppendDateAndTime Should append timestamp to the file name? If true, the final file name 
  *          will be fileName_timestamp.csv else fileName.csv 
  * @throws IOException
  */
 public CSVFileWriter(String filePathWithoutFileName, String fileName, boolean shouldAppendDateAndTime) 
  throws IOException{
  
  if(shouldAppendDateAndTime){
   DateFormat dateFormate = new SimpleDateFormat("yyyy-MM-dd");
   String date = dateFormate.format(new Date());
   
   DateFormat timeFormat = new SimpleDateFormat("hh-mm-ss");
   String time = timeFormat.format(new Date());
   
   csvFilePath = filePathWithoutFileName + FILE_SEPARATOR + fileName + "_" + date + "-" + time + ".csv";
  } else {
   csvFilePath = filePathWithoutFileName + FILE_SEPARATOR + fileName + ".csv";
  }
  
  fw = createFileWriter(csvFilePath);
  outputStr = new StringBuilder();
 }
 
 /**
  * Add row in the CSV file.
  * @param commaSeperatedStr Row data. The comma separated string.
  */
 public void addRow(String commaSeperatedStr){
  if (outputStr == null)
   outputStr = new StringBuilder();
  
  if (csvFilePath == null)
   return;
  
  outputStr.append(commaSeperatedStr);
  outputStr.append("\n");
  
  if (outputStr.length() < 5000) 
   return;  

  //if output string size more than 5000 flush to the file
  try {   
   fw.write(outputStr.toString().toCharArray());
   fw.flush();
   outputStr = new StringBuilder();
  }catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 /**
  * Stop file writing
  */
 public void stopFileWriting(){  
  try {
   if (outputStr != null) {
     if(outputStr.toString().trim().length() != 0) {
      fw.write(outputStr.toString().toCharArray());
     }
     
     fw.close();
     fw = null;
     csvFilePath = null;
     outputStr = null;
   } 
  }catch (Exception e) {
   e.printStackTrace();
  }
 }

 /**
  * Get CVS file path
  * @return
  */
 public String getCSVFilePath(){
  return csvFilePath;
 }

 private FileWriter createFileWriter(String fileName) throws IOException{
  File aFile = new File(fileName);  
  FileWriter fw = new FileWriter(aFile, true);
  return fw;
 }
}
CSV File Writing Test Class:
package com.blogspot.maheshmhetre.util;
import java.io.IOException;

import wt.util.WTException;

public class TestCSVFileWriter {

 private static final char COMMA_SEPERATOR = ',';
 private static String CSV_FILE_DIR = System.getProperty("user.dir");
 
 private CSVFileWriter csvFileWriter = null;
 
 public static void main(String[] args) {

  TestCSVFileWriter fileWritingTest = new TestCSVFileWriter();
  try {
   for (int i = 0; i < 10; i++) {
    //adding random cell data. Add actual data here
    fileWritingTest.addRowToOutputCSVFile(i + "qq", i + 2 + "tt", i + 5 + "zz");
   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (fileWritingTest.csvFileWriter != null) {
    fileWritingTest.csvFileWriter.stopFileWriting();
   }
  }
 }
//Change method signature according to your output CSV file format
private void addRowToOutputCSVFile(String cellOne, String cellTwo, String cellThree) throws WTException{
//Create output CSV file if not available
try { if(csvFileWriter == null){ //pass your desired file dir csvFileWriter = new CSVFileWriter(CSV_FILE_DIR, "MyCSVFile", true); } } catch (IOException e) { throw new WTException("Error while creating CSV File. " + e); } try { csvFileWriter.addRow(cellOne + COMMA_SEPERATOR + cellTwo + COMMA_SEPERATOR + cellThree); } catch (Exception e) { throw new WTException(e); } } }
You can download code here: CSVFileWriter TestCSVFileWriter

No comments: