?
Solved

How to read data from a .csv file

Posted on 2006-05-28
10
Medium Priority
?
780 Views
Last Modified: 2012-05-05
I have an application where I used Jakarta POI-HSSF API to read data from an excel .xls file. I pass the fileInputStream to the method and it gives me an arraylist of rocords. One record contains an arraylist of cells.

Now instead of reading data from a .xls file, I need t read data from a .csv file, but I am not sure how to read data from a .csv file. I would greatly appreciate if somebody can recommend an API or have code for this.

0
Comment
Question by:royalcyber
9 Comments
 
LVL 92

Accepted Solution

by:
objects earned 1200 total points
ID: 16781982
0
 
LVL 10

Expert Comment

by:mukundha_expert
ID: 16782225
This Code will Get a ArrayList of Records from the CSV file and each record inturn will contain a arraylist of cells. This is working fine,


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.StringTokenizer;

public class CSV {

      public static void main(String[] args)
                  throws IOException{
            
            FileReader fileR = new FileReader("test.csv");
            BufferedReader bCsv = new BufferedReader(fileR);
            String out="";
            ArrayList record = new ArrayList();
            //Adding Recors to the ArrayList Record
            while(out!=null){
                  out = bCsv.readLine();
                  
                  if(out==null){
                        break;
                  }
                  //Adding cells to the ArrayList cells
                  ArrayList cells = new ArrayList();
                  StringTokenizer tokens = new StringTokenizer(out,",");
                  while(tokens.hasMoreElements()){
                        cells.add(tokens.nextToken());
                  }
                  record.add(cells);
            }
            
            //Iterating thro the Records
            ListIterator recordIterator = record.listIterator();
            
            while(recordIterator.hasNext())      {
                  ArrayList cell = (ArrayList)recordIterator.next();
                  
                  ListIterator cellIterator = cell.listIterator();
                  while(cellIterator.hasNext()){
                        System.out.print((String)cellIterator.next()+" ");
                  }
                  System.out.println("");
            }
      }
}


Cheers,
Mukundh      
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 14

Expert Comment

by:hoomanv
ID: 16782250
notice that using StringTokenizer is not the proper way of reading csv files because of its weakness in both handling empty strings and also tokenizing quoted strings that have commas inside them
0
 
LVL 10

Assisted Solution

by:mukundha_expert
mukundha_expert earned 800 total points
ID: 16783283
Hi, Try this new code. This one works for empty strings as well as quoted strings that have commas.



import java.util.ArrayList;

public class CSVAdap {
      
      public static ArrayList columnList(String row)
      {
            ArrayList cell = new ArrayList();
            int lastPoint = 0;
            int i=0;
            for(i=0;i<row.length();i++)
            {
                  char ch = row.charAt(i);
                  
                  if(ch == '"'){
                        int j=row.indexOf('"',i+3);
                        String temp = row.substring(i+2,j+1);
                        cell.add(temp);
                        i=j+3;
                        lastPoint = i+1;
                  }
                  if(ch==',')
                  {
                        String temp = row.substring(lastPoint,i);
                        cell.add(temp);
                        lastPoint = i+1;
                        
                  }
            }
            
            if(lastPoint<i){
                  String temp = row.substring(lastPoint,i);
                  cell.add(temp);
            }
            return cell;
      }      

}




import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.ListIterator;

public class CSV1 {
      public static void main(String[] args)
      throws IOException{

      FileReader fileR = new FileReader("test.csv");
      BufferedReader bCsv = new BufferedReader(fileR);
      String out="";
      ArrayList record = new ArrayList();
      //Adding Recors to the ArrayList Record
      while(out!=null){
            
            out = bCsv.readLine();
            ArrayList cell = new ArrayList();
            if(out==null){
                  break;
            }
            cell = CSVAdap.columnList(out);
            record.add(cell);
      }

      ListIterator recordIterator = record.listIterator();
      while(recordIterator.hasNext())      {
            ArrayList cell = (ArrayList)recordIterator.next();
            
            ListIterator cellIterator = cell.listIterator();
            while(cellIterator.hasNext()){
                  System.out.print((String)cellIterator.next()+" -- ");
            }
            System.out.println("");
      }

      }
}

Cheers,
Mukundh
0
 
LVL 16

Expert Comment

by:Joe
ID: 16784339
Another lib you can try:

http://sourceforge.net/projects/pzfilereader


Joe
0
 

Author Comment

by:royalcyber
ID: 16792139
Thank you very much guys for all your replies

Mukhand I tried your code but somehow it gives me the following error

String index out of range: -1399

would you know why I am getting this error

Thanks
0
 
LVL 10

Expert Comment

by:mukundha_expert
ID: 16799208
I tried in my system. its not showing any errors. I created the .csv file using Excel. If you could send ur .csv file to my mail. i can check it and tell you. <mail removed by Venabili>

cheers,
Mukundh
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16799426
No e-mail IDs on question-pages please.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month14 days, 7 hours left to enroll

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question