Reads a comma separated value file(CSV) using java
package config.java.custom.tasks; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; import ariba.util.core.StringUtil; import com.sun.org.apache.xml.internal.utils.FastStringBuffer; public class CSVParser { FastStringBuffer fsbRecordsWithFileOrAQLError = null;// buffer file read errors // FastStringBuffer fsbRecordsWithIncorrectAmount = null;// buffer for amount mismatch FastStringBuffer fsbRecordsWithIncorrectFieldCount = null;// buffer for incorrect number of fields in row FastStringBuffer fsbRecordsWithNullValues = null;// buffer for null fields in row private static String sCSVFile = null; private static ArrayList alUniqueKey = null; private static HashMap alCSVLineValue = null; protected static String sErrrorFile = null; private static ArrayList sample=new ArrayList(); static boolean bError; // true if there is any error in the entire validation process public static void main(String[] args) { boolean bFileRead = true; if (null == sCSVFile) sCSVFile = "D:/csvread/sample.csv"; System.out.println("sCSVFile - "+sCSVFile); // Read the Tier file into array lists System.out.println("Run - 1 : Reading the CSV file : "+sCSVFile); bFileRead = readCSV(); System.out.println("Run - 2 : bFileRead: "+bFileRead); System.out.println("Run - 3 : bError: "+bError); if (bFileRead) { try { System.out.println("Run - 4 : CSV file has been read successfully and can be referenced through alCSVLineValue-HashMap"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /* readCSV(): This method reads the CSV file into an arraylist/HashMap */ protected static boolean readCSV () { boolean bFileReadSucess = true; String sExceptionIfAny = null; String sLineRead = null; alUniqueKey = new ArrayList(); alCSVLineValue = new HashMap(); String sBreakCharacters = ","; String sUniqueName=null; System.out.println("inside csv file read"); try { RandomAccessFile rafTierCSVFile = new RandomAccessFile(sCSVFile, "r"); int iLineCount = 0; int indexCount=0; String sLineCount = null; // Read the file line by line while ((sLineRead = rafTierCSVFile.readLine()) != null) { ArrayList eachLine=new ArrayList(); ArrayList eachValue=new ArrayList(); iLineCount++; sLineCount = String.valueOf(iLineCount); sLineRead = sLineRead.trim(); System.out.println("inside csv file read2"); System.out.println(sLineRead); StringTokenizer st = new StringTokenizer(sLineRead,sBreakCharacters); // Skip the record if it does not have 8 fields System.out.println(st.countTokens()); if ((st.countTokens()-1) != 7 )//This validation is used ONLY when the length of each row is already known;else it can be skipped { System.out.println ("No. of columns in a row is incorrect"); bError = true; System.out.println(sLineCount+"["+st.countTokens()+"], "); continue; } System.out.println("Delimiter checked"); // convert delimited string into vector of strings while (st.hasMoreTokens()) { //get next token and store it in the array eachLine.add(st.nextToken()); } System.out.println ("ArrayList created: "); // remove quotes if the cav contains values enclosed within double-quotes sUniqueName = removeQuotes(((String)eachLine.get(0)).trim());//assuming that the 1st value is the UniqueKey System.out.println ("readTierCSV - 1: sUniqueName: " + sUniqueName); //similarly other values of the line/row can be read for(int z=0;z<eachLine.size();z++) { System.out.println("inside the row"); eachValue.add(removeQuotes(((String)eachLine.get(z)).trim())); //System.out.println("row"+z+removeQuotes(((String)eachLine.get(z)).trim())); } FastStringBuffer fsbNullValue = new FastStringBuffer(); // Check for null values fsbNullValue.append((StringUtil.nullOrEmptyOrBlankString(sUniqueName) ? " UniqueName " : "")); // similarly other values can be null checked if (fsbNullValue.length() > 0) { bError = true; fsbNullValue.append("Line#"+sLineCount.toString()); System.out.println("readTierCSV - 2: NullValue: " + fsbNullValue.toString()); fsbNullValue.append(" "); } else { alCSVLineValue.put(sUniqueName,eachValue); alUniqueKey.add(sUniqueName); } } // build a Hashmap with any one Uniquekey so that the corresponding row can be retrieved based on a UniqueKey for(int z=0;z<alUniqueKey.size();z++) { System.out.println("inside HashMap"); System.out.println(alCSVLineValue.get(alUniqueKey.get(z))); sample=((ArrayList)alCSVLineValue.get(alUniqueKey.get(z))); for(int h=0;h<sample.size();h++) { System.out.println(sample.get(h)); } } rafTierCSVFile.close(); } catch (FileNotFoundException fnfExp) { bFileReadSucess = false; sExceptionIfAny = fnfExp.getMessage(); } catch(IOException ioExp) { bFileReadSucess = false; sExceptionIfAny = ioExp.getMessage(); } catch(Exception exp) { bFileReadSucess = false; sExceptionIfAny = exp.getMessage(); } finally { if (!bFileReadSucess) { bError = true; System.out.println ("readTierCSV - 2: Error opening file: " + sCSVFile); System.out.println ("readTierCSV-3: Error opening file - Exception: " + sExceptionIfAny); } return bFileReadSucess; } } /* This method removes double quotes from the beginingand end of a string This was added to handle the special case where a particular field contained double quotes */ protected static String removeQuotes(String sField) { System.out.println("removeQuotes - 1: incoming sField: "+sField); String sQuotes = """; if (sField != null) { sField = (sField.startsWith(sQuotes)) ? (sField.substring(1)) : sField; //System.out.println("removeQuotes - 2: sField after removing first double quotes: "+sField); sField = (sField.endsWith(sQuotes)) ? (sField.substring(0, (sField.length()-1))) : sField; //System.out.println("removeQuotes - 3: sField after removing second double quotes: "+sField); } //System.out.println("removeQuotes - 4: returning sField: "+sField); return sField; } }