Reputation: 4672
I am validating a particular column in a CSV file , I have basically two approaches i.e
Approach 1
I can Read the CSV file line by line with a BufferedReader
and Stop when
I hit a line that startsWith the thing I'm looking for
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(item.getInputStream()));
String strLine = "";
StringTokenizer st = null;
String value = "";
while ((strLine = br.readLine()) != null) {
st = new StringTokenizer(strLine, ",");
while (st.hasMoreTokens()) {
value = st.nextToken();
if ((value != null) && (("MyString1".equals(value)
|| ("MyString2".equals(value)
|| ("MyString3".equals(value))) {
// Send error Message
}
}
}
Second Approach is use a String.split as below
Scanner s = new Scanner(item.getInputStream());
while(s.hasNextLine()) {
String[] fields = s.nextLine().split("\\s*,\\s*", -1);
for(int i = 0;i < fields.length;i++) {
if(!"".equals(fields[i]) && ...
}
}
s.close();
Please suggest a better approach
Upvotes: 0
Views: 4504
Reputation: 39570
Don't write your own CSV parser. CSV is actually more complicated than you might at first guess. (Examples: multi-line values, encapsulated fields, escaped characters, and more. Commas don't always separate fields!)
Use opencsv, which is a full-featured pure-Java CSV parser.
This parser will easily let you loop over a CSV file, and process individual columns and rows. Examples are given in the link above.
Edit: Also, I forgot to mention, it is Apache2 licensed, so it can safely be embedded in commercial projects!
Upvotes: 1