File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes I/O and Streams and the fly likes Reading csv file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Reading csv file " Watch "Reading csv file " New topic

Reading csv file

Rehana Shaik
Ranch Hand

Joined: Jan 03, 2003
Posts: 33
Hi, my requirement is to read from a .csv (comma seprated version) file. Presently what i am doing is i am reading each line and creating stringtokenizer with comma(,)and reading one by one element.Is this approach is correct or is there any other procedure to read .csv files in java.Thanks in advance
Joe Ess

Joined: Oct 29, 2001
Posts: 9167

That's how I'd do it.

[How To Ask Questions On JavaRanch]
David Peterson
Ranch Hand

Joined: Oct 14, 2001
Posts: 154
The trouble with CSV is that there are different flavours. You need to find out the exact spec of the CSV you're trying to import.
For example, some formats allow commas or line-breaks within items. Usually this is done by wrapping the item in single- or double-quotes (e.g. "bloggs, f"). If you simply look at commas you'll end up breaking this item into two pieces when it should be considered as one. Note: there are also different conventions about how to escape quotes within an item.
Once you know which flavour of CSV you're after, search Google. Other people will definitely have solved the problem already. Don't reinvent the wheel.
Rehana Shaik
Ranch Hand

Joined: Jan 03, 2003
Posts: 33
my file will contain ,(comma) only .Other than that no special characters are allowed.but my problem is sometimes i will get blank values in between.but StringTokenizer is ignoring blank.Presently we are using jdk1.3 so that i can't use string.split(",").If any one knows the solution please let me know. Thanks in advance
Pratibha Malhotra
Ranch Hand

Joined: Dec 21, 2003
Posts: 199
Solution depends on what kind of file do you want to upload.
In case what u want to upload is an excel, you can use jakarta's POI.
However, in case what you have is an .csv , you can use a utility called SQL Loader.

~ Pratibha Malhotra<br /> <br />Sun Certified Java Programmer<br />SCEA 1.4 (In Progress)<br />~~~~~~~~~~~~~~~~~~~~~~~~~~~<br />"Many of life's failures are people who did not realize how close they were to success when they gave up!!"
Richard Rodger

Joined: Jan 07, 2005
Posts: 17
You can't use StringTokenizer as CSV allows both commans *and* newlines inside quoted fields.

Use a dedicated CSV parser -
[ January 10, 2005: Message edited by: Richard Rodger ]

Richard Rodger<br /><a href="" target="_blank" rel="nofollow"></a>
I agree. Here's the link:
subject: Reading csv file
jQuery in Action, 3rd edition