• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to read .csv file

 
Angela D'souza
Ranch Hand
Posts: 469
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
How to read .csv file in java?
Thanks,
Angela
 
James Swan
Ranch Hand
Posts: 403
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, well .csv files have data within a row delimited by commas.
So given this you can make use of the StringTokenizer class to easily return an enumeration of the data elements per row.
Here is an outline of the sort of thing you would want to do:
 
Angela D'souza
Ranch Hand
Posts: 469
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Is csv file format same on different OS?
Angela
 
James Swan
Ranch Hand
Posts: 403
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it's the same on different OS's.
It's just a text file that uses commas to delimit data.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that StringTokenizer won't work the way you want if some of the values are allowed to be blank. E.g. in the input
Allan,Burt,Carl
Amelia,,Charlotte
Ace,Butch,Cujo
the second field of the second line is probably supposed to be blank. However a StringTokenizer will treat Charlotte as the value for the second field, and there will be no third field for that line. Which could be a problem. The easiest solution is probably to use SDK 1.4, which adds a split() method to String:
 
James Swan
Ranch Hand
Posts: 403
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmmm, that seems a rather annoying "feature" of the 1.3 StringTokenizer.
Thanks for the tip Jim.
 
Steve Deadsea
Ranch Hand
Posts: 125
 
Younes Essouabni
Ranch Hand
Posts: 479
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Steve,
I've downloaded your utility. My problem is that the separator in the file that i receive is a semicolon ( ; ) instead of a coma (,). I went around the methods to see if it was possible to set a different separator, but couldn't find anything. Do you have any suggestion, or will I have to parse all the file and replace the semicolon by a coma. The file I'm receiving should be an Excell file.
Thx in adance for any answers
[ January 03, 2003: Message edited by: Younes Essouabni ]
 
David Weitzman
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In one objectmentor.com article a CSV parser is created using Test Driven Development (don't look at the one labeled 'circa 1998'--it's not nearly as easy to work with). If you understand Finite State Machines the code there should be easy to modify, and if you don't than look at the method charEvent(char) and change it to understand semicolons.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic