Tuesday, May 28, 2013

Read csv file using java

In This example I have to demonstrate, How to read comma separated text file in java 






  import java.io.BufferedReader;   

  import java.io.FileReader;   

  import java.io.IOException;   

  public class Comma {   

      public static void main(String args[]){   
           try {
// for csv file just change file name 
                BufferedReader in = new BufferedReader(   
                          new FileReader("D:\\uttam\\files\\comma.txt"));   
                String str;   
                str = in.readLine();   
                //System.out.println(str);   
                String[] ar =str.split(",");   
                for(int i=0;i<ar.length;i++){   
                     System.out.print(ar[i]+"\t");   
                }   
                while ((str = in.readLine()) != null) {   
                     ar=str.split(",");   
                     System.out.println();   
                     for(int i=0;i<ar.length;i++){   
                               System.out.print(ar[i]+"\t");   
                     }   
                }   
                in.close();   
           } catch (IOException e) {   
           System.out.println("File Read Error");   
           }  
      }            
 }   

No comments:

Post a Comment