Friday, April 4, 2014

How to separate the data from the csv file using java?



Sample CSV file

employee ID,Name,City
101,Peter,xxxxxx
102,Adrew,xxxxxx
103,Simon,yyyyyy
104,Thomas,xxxxxx
105,David,yyyyyy
106,Issac,zzzzzz
107,James,zzzzzz
108,Jacob,zzzzzz
109,John,xxxxxx
110,Stephan,yyyyyy

Employee.java

public class Employee
{
    private String id;
    private String name;
    private String city;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}


 MainClass.java

import demo.Student;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;

public class MainClass {
    public static void main(String args[]) throws FileNotFoundException, IOException
    {
    BufferedReader br=new BufferedReader(new FileReader("D:\\Project\\src\\Demo2\\employee.csv"));
    String str="";
    Vector< Employee >Emp_list=new Vector< Employee >();
    while((str=br.readLine())!=null)
    {
        String split[]=str.split(",");
        Empl e=new Empl();
        e.setId(split[0]);
        e.setName(split[1]);
        e.setCity(split[2]);
        Emp_list.add(e);
    }  
     Vector<Vector>v_List=new Vector<Vector>();
      
        for(int i=0;i<Emp_list.size();i++)
        {
            Empl e_data=Emp_list.elementAt(i);
            String city=e_data.getCity();
            boolean newlist=true;
           
            for(int j=0;j<v_List.size();j++)
            {
                Vector l_v_list=v_List.elementAt(j);
                Empl d_City=(Empl)l_v_list.elementAt(0);
                if(d_City.getCity().equalsIgnoreCase(city))
                {
                    l_v_list.add(e_data);
                    newlist=false;
                    break;
                }
            }      
            if(newlist==true)
            {
                Vector new_List=new Vector();
                new_List.add(e_data);
                v_List.add(new_List);
            }
        }
       
        for(int i=0;i<v_List.size();i++)
        {
            for(int j=0;j<v_List.elementAt(i).size();j++)
            {
                Empl data=(Empl)v_List.elementAt(i).elementAt(j);
                System.out.println(data.getId()+","+data.getName()+","+data.getCity());
            }
            System.out.println("-------------------------------");
        }
    }
}

 
Output

employee ID,Name,City
101,Peter,xxxxxx
102,Adrew,xxxxxx
104,Thomas,xxxxxx
109,John,xxxxxx
-------------------------------
103,Simon,yyyyyy
105,David,yyyyyy
110,Stephan,yyyyyy 
-------------------------------
106,Issac,zzzzzz
107,James,zzzzzz
108,Jacob,zzzzzz