Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

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

How package names to be formed?

Many times I came across Java developers who are not clear how the package names to be formed. Here I am trying to explain on how package names to be formed.

Generally package name start with reverse domain name resolution and later the application and module name and then finally the area you are working
The package name can be formed as below
<TLD>.<org/domain name>.<application name>.<module name>.<sub-module name>.<working area>.<more down level if needed>

Consider below is the scenario
  • Organization domain name: www.myOrg.com
  • Application Name: Windchill
  • Module Name: Lifecycle
  • Sub Module Name: Assignment
  • Working Area: Participants
Following the above pattern my package name will be
com.myorg.windchill.lifecycle.assignment.participants

I always try emphasis on the deep level or extended package name so that the package will have only specific/relevant classes available. Please try to avoid putting many class in a single package and try to put them into very specific package.

Hope this is a useful information.