1 Reply Latest reply on Nov 6, 2007 7:58 PM by 807603

    To read and write from/to a CSV file

    807603
      Hi,

      This is a sample code piece I developed to read and write from/to a CSV file.

      import java.io.*;
      import java.util.*;

      public class sampleCSVIO
      {
      //Declaring global variables
           private static final String CLASS_NAME = "sampleCSVIO";
           
           public sampleCSVIO()
           {
                super();
           }

           public static void main(String[] args)
           {
                System.out.println(CLASS_NAME +" :: Main method starting...");
                
                //Varibale to store the input file path
                String filePath = "D:\\Aswini\\Temp\\SampleCSVFile1.csv";
                System.out.println(CLASS_NAME + " :: filePath :: "+filePath);
                //Variable to store the file encoding
                String fileEncoding = "ISO8859_1";
                String lineContent= null;
                //Vector variable to contain the user unique names
                Vector UniqueNameList = new Vector();
                //Vector variable to contain the roles
                Vector RoleList = new Vector();
                //Boolean variable to check if the role exists
                boolean roleExists = false;
                //Boolean variable to check if the user unique name exists
                boolean uniqueNameExists = false;
                
                //final int roleHeaderSize = 2;
                //final String header_RoleCSV[] = {"RoleName","Active"};
                //String variable for the headers to be defined in the UserRoles.csv file
                final String header_Roles = "RoleName,Active";
                //String variable for the headers to be defined in the UserUniqueName.csv file
                final String header_User = "UserUniqueName,Active";
                
                //Read the contents of the input file
                Vector dataLines = readAllLines(filePath,fileEncoding);
                System.out.println(CLASS_NAME + " :: dataLines :: "+dataLines);
                
                for(int i=1; i<dataLines.size(); i++)
                {
                     lineContent = (dataLines.elementAt(i)).toString();
                     System.out.println(CLASS_NAME + " :: lineContent :: "+lineContent);
                     
                     StringTokenizer st = new StringTokenizer(lineContent,",");
                     String userUniqueName = st.nextToken();
                     System.out.println(CLASS_NAME + " :: User Unique Name :: "+userUniqueName);
                     
                     //Chcek if the user is already in the list. If the user is not there, then add it to the list.
                     for (int j=0; j < UniqueNameList.size(); j++)
                     {
                          String uniqueName = (String)UniqueNameList.elementAt(j);
                          System.out.println(CLASS_NAME + " :: User ID:: "+uniqueName);
                          if (uniqueName.equals(userUniqueName))
                          {
                               System.out.println(CLASS_NAME + " :: User is already there in the list. Setting the flag to true...");
                               uniqueNameExists = true;
                          }
                     }
                     
                     if (!uniqueNameExists)
                     {
                          UniqueNameList.add(userUniqueName);
                     System.out.println(CLASS_NAME + " :: UniqueNameList :: "+UniqueNameList);
                     }
                     
                     String userRole = st.nextToken();
                     System.out.println(CLASS_NAME + " :: User Role :: "+userRole);
                     
                     //Chcek if the role is already in the list. If the role is not there, then add it to the list.
                     for (int k=0; k < RoleList.size(); k++)
                     {
                          String userRoleName = (String)RoleList.elementAt(k);
                          System.out.println(CLASS_NAME + " :: User Role Name:: "+userRoleName);
                          if (userRoleName.equals(userRole))
                          {
                               System.out.println(CLASS_NAME + " :: Role is already there in the list. Setting the flag to true...");
                               roleExists = true;
                          }
                     }
                     
                     if (!roleExists)
                     {
                     RoleList.add(userRole);
                     System.out.println(CLASS_NAME + " :: RoleList :: "+RoleList);
                     }
                     
                     //Reset the flags
                     uniqueNameExists = false;
                     roleExists = false;
                }
                
                createRoleCSV(RoleList,header_Roles);
                createUserCSV(UniqueNameList,header_User);
                System.out.println(CLASS_NAME +" :: Exiting Main method ...");
           }
           
           public static Vector readAllLines(String flPath, String encoding)
           {
                System.out.println(CLASS_NAME +" :: Entering method readAllLines()...");
                Vector allLines = new Vector();
                int count = 1;
                try
                {
                     System.out.println(CLASS_NAME + " :: Inside try block...");
                     FileReader fileReader = new FileReader(flPath);
                     System.out.println(CLASS_NAME + " :: fileReader :: "+fileReader);
                     BufferedReader br = new BufferedReader(fileReader);
                     System.out.println(CLASS_NAME + " :: br :: "+br);
                     while (br.ready())
                     {
                          String line = br.readLine();
                          System.out.println(CLASS_NAME + " :: line :: "+line);
                          allLines.addElement(line);
                          br.mark(0);
                          count++;
                     }
                     System.out.println(CLASS_NAME + " :: Exiting try block...");
                }
                catch(FileNotFoundException e)
                {
                     System.out.println(CLASS_NAME + " :: FileNotFound Exception occurred...");
                     e.printStackTrace();
                }
                catch(IOException e)
                {
                     System.out.println(CLASS_NAME + " :: IO Exception occurred...");
                     e.printStackTrace();
                }
                
                int totalLinesRead = count-1;
                System.out.println(CLASS_NAME + " :: Total number of lines read :: "+totalLinesRead);
                
                System.out.println(CLASS_NAME +" :: Exiting method readAllLines()...");
                return allLines;
           }
           
           public static void createRoleCSV(Vector roles,String header)
           {
                System.out.println(CLASS_NAME +" :: Entering method createRoleCSV()...");
                FileWriter fw = null;
                BufferedWriter bw = null;
                
                try
                {
                     System.out.println(CLASS_NAME + " :: Inside try block...");
                     fw = new FileWriter("D:\\Aswini\\Temp\\UserRoles.csv");
                     bw = new BufferedWriter(fw);
                     
                     //Write the header part to the CSV file
                     System.out.println(CLASS_NAME + " :: header :: "+header);
                     bw.write(header,0,checkLength(header));
                     
                     bw.newLine();
                     
                     int roleSize = roles.size();
                     System.out.println(CLASS_NAME + " :: roleSize :: "+roleSize);
                     int eofIndicator = roleSize-1;
                     System.out.println(CLASS_NAME + " :: eofIndicator :: "+eofIndicator);
                     
                     //Write the detail data to the CSV file
                     for(int j=0; j < roles.size(); j++)
                     {

                          
                          String roleName = (String)roles.elementAt(j);
                          System.out.println(CLASS_NAME + " :: roleName :: "+roleName);
                          
                          try
                          {
                               if (roleName.startsWith("A")||roleName.startsWith("a"))
                               {
                                    continue;
                               }
                               else
                               {
                               bw.write("\"",0,1);
                               bw.write(roleName,0,checkLength(roleName));
                               bw.write("\",\"",0,3);
                               bw.write("true",0,4);
                               bw.write("\"",0,1);
                               
                               }
                               
                               //Check for end of file
                               if(j == eofIndicator-1)
                               {
                                    System.out.println(CLASS_NAME + " :: Reached end of file...");
                               }
                               else
                               {
                                    bw.newLine();
                               }                         
                          }
                          catch(Exception e)
                          {
                               System.out.println(CLASS_NAME + " :: Exception occurred..."+e);
                          }
                     }
                     
                     System.out.println(CLASS_NAME + " :: Exiting try block...");
                }
                catch(Exception e)
                {
                     System.out.println(CLASS_NAME + " :: Exception occurred...");
                     e.printStackTrace();               
                }
                
                try
                {
                bw.close();
                fw.close();
                }
                catch(Exception e)
                {
                     System.out.println(CLASS_NAME + " :: Exception occurred..." +e);
                }
                
                System.out.println(CLASS_NAME +" :: Exiting method createRoleCSV()...");
           }
           
           public static void createUserCSV(Vector users,String header)
           {
                System.out.println(CLASS_NAME +" :: Entering method createUserCSV()...");
                FileWriter fw = null;
                BufferedWriter bw = null;
                
                try
                {
                     System.out.println(CLASS_NAME + " :: Inside try block...");
                     fw = new FileWriter("D:\\Aswini\\Temp\\UserUniqueName.csv");
                     bw = new BufferedWriter(fw);
                     
                     //Write the header part to the CSV file
                     System.out.println(CLASS_NAME + " :: header :: "+header);
                     bw.write(header,0,checkLength(header));
                     bw.newLine();
                     
                     int userSize = users.size();
                     System.out.println(CLASS_NAME + " :: userSize :: "+userSize);
                     int eofIndicator = userSize-1;
                     System.out.println(CLASS_NAME + " :: eofIndicator :: "+eofIndicator);
                     
                     //Write the detail data to the CSV file
                     for(int j=0; j < users.size(); j++)
                     {
                          String userID = (String)users.elementAt(j);
                          System.out.println(CLASS_NAME + " :: userID :: "+userID);
                          
                          try
                          {
                               if (userID.startsWith("A")||userID.startsWith("a"))
                               {
                                    continue;
                               }
                               else
                               {
                               bw.write("\"",0,1);
                               bw.write(userID,0,checkLength(userID));
                               bw.write("\",\"",0,3);
                               bw.write("true",0,4);
                               bw.write("\"",0,1);
                               
                               }
                               
                               //Check for end of file
                               if(j == eofIndicator-1)
                               {
                                    System.out.println(CLASS_NAME + " :: Reached end of file...");
                               }
                               else
                               {
                                    bw.newLine();
                               }                         
                          }
                          catch(Exception e)
                          {
                               System.out.println(CLASS_NAME + " :: Exception occurred..."+e);
                          }
                     }
                     
                     System.out.println(CLASS_NAME + " :: Exiting try block...");
                }
                catch(Exception e)
                {
                     System.out.println(CLASS_NAME + " :: Exception occurred...");
                     e.printStackTrace();               
                }
                
                try
                {
                bw.close();
                fw.close();
                }
                catch(Exception e)
                {
                     System.out.println(CLASS_NAME + " :: Exception occurred..." +e);
                }
                
                System.out.println(CLASS_NAME +" :: Exiting method createRoleCSV()...");
           }     
           
           public static int checkLength(String str)
           {
                System.out.println(CLASS_NAME +" :: Entering method checkLength()...");
                if(str == "" || str == null)
                {
                     System.out.println(CLASS_NAME +" :: Returning 0. Exiting method checkLength()...");
                     return 0;
                }
                else
                {
                     System.out.println(CLASS_NAME +" :: Exiting method checkLength()...");
                     return str.length();
                }
           }
      }