开发者

Validating a particular column in CSV

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 = "";
    S开发者_如何学编程tringTokenizer 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


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜