CsvParser

import java.util.ArrayList;

public class CsvParser {
	
	public static final String SEPARATOR = ",";
	public static final char QUOTE = '"';
	
	// parse the csv line into an ArrayList of values
	public static ArrayList parse(String line) throws Exception {
		ArrayList list = null;
		
		if (line == null) {
			// return null if input line is null
		}
		else {
			list = new ArrayList();
			
			if (line.length() == 0) {
				// return an empty line if the input is an empty line
				list.add(line);
			}
			else {
				StringBuffer sb = new StringBuffer();
				
				String[] a = line.split(SEPARATOR);
				for (int i=0; i<a.length; i++) {
					sb.append(a[i]);
					
					// count the no. of double quote
					int count = 0;
					for (int m=0; m<sb.length(); m++) {
						if (sb.charAt(m) == QUOTE) {
							count++;
						}
					}
					
					if (count > 0) { // has double-quote
						if (count % 2 == 0) { // complete token
							sb = new StringBuffer(sb.toString().trim());
							
							if (sb.charAt(0) == QUOTE && sb.charAt(sb.length()-1) == QUOTE) {
								sb.deleteCharAt(sb.length()-1); // remove trailing double-quote
								sb.deleteCharAt(0); // remove leading double-quote
								
								for (int h=0; h<sb.length(); h++) {
									if (sb.charAt(h) == QUOTE) {
										int nextPos = h+1;
										if (nextPos < sb.length() && sb.charAt(nextPos) == QUOTE) { // if escaped by another double-quote
											sb.replace(h, nextPos+1, String.valueOf(QUOTE)); // replace escaped double-quotes
										}
										else {
											throw new Exception("a literal double-quote should be escaped by another double-quote");
										}
									}
								}
								
								// add to list
								list.add(sb.toString());
								
								// reset buffer
								sb.setLength(0);
							}
							else {
								throw new Exception("field containing commas and double-quotes must be quoted");
							}
						}
						else { // incomplete token
							if (i < a.length-1) {
								// append the removed separator
								sb.append(SEPARATOR);
								
								// continue to append the next token
							}
							else {
								// no more token left
								throw new Exception("Incomplete token");
							}
						}
					}
					else { // no double quote
						// add to list
						list.add(sb.toString().trim());
						
						// reset buffer
						sb.setLength(0);
					}
				}
			}
		}
		
		return list;
	}

	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值