CSV文件解析

CSV(逗號分隔值文件格式)

       逗號分隔值(Comma-Separated Values,CSV,有時也稱爲字符分隔值,由於分隔字符也能夠不是逗號),其文件以純文本形式存儲表格數據(數字和文本)。純文本意味着該文件是一個 字符序列,不含必須像二進制數字那樣被解讀的數據。CSV文件由任意數目的記錄組成,記錄間以某種換行符分隔;每條記錄由 字段組成,字段間的分隔符是其它字符或字符串,最多見的是逗號或 製表符。一般,全部記錄都有徹底相同的字段序列。CSV文件格式的通用標準並不存在,可是在RFC 4180中有基礎性的描述。使用的字符編碼一樣沒有被指定,可是7-bit ASCII是最基本的通用編碼。
      java解析CSV文件的通用方法:
      其它輔組類參考    http://www.cnblogs.com/wshsdlau/p/5643862.html
       
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.boguan.bte.service.common.IExcelRowReader;

/**
 * 名稱: CsvParser.java<br>
 * 描述: <br>
 * 類型: JAVA<br>
 * 最近修改時間:2016年7月6日 上午10:22:34<br>
 * 
 * @since 2016年7月6日
 * @author 
 */
public class CsvReader {

    /**
     * Space mark , ; : etc.
     */
    private String spaceMark = ",";

    /**
     * CSV固定只有SHEET_NUM=0
     */
    private final static int SHEET_NUM = 0;

    /**
     * Contructor
     * 
     * @param inputCsvFile
     */
    public CsvReader() {
    }

    /**
     * 行讀取
     */
    private IExcelRowReader rowReader;

    public void setRowReader(IExcelRowReader rowReader) {
        this.rowReader = rowReader;
    }

    /**
     * 從CSV文件中獲取數組
     * 
     * @return
     * @throws IOException
     */
    public void process(String inputCsvFile) throws IOException {
        BufferedReader in = null;
        try {
            in = new BufferedReader(new FileReader(inputCsvFile));
            List<List<String>> retval = new ArrayList<List<String>>();
            String regExp = getRegExp();
            String strLine;
            String str = "";
            int rowNum = 0;
            List<String> listTemp = null;
            while ((strLine = in.readLine()) != null) {
                Pattern pattern = Pattern.compile(regExp);
                Matcher matcher = pattern.matcher(strLine);
                listTemp = new ArrayList<String>();
                while (matcher.find()) {
                    str = matcher.group();
                    str = str.trim();
                    if (str.endsWith(spaceMark)) {
                        str = str.substring(0, str.length() - 1);
                        str = str.trim();
                    }
                    if (str.startsWith("\"") && str.endsWith("\"")) {
                        str = str.substring(1, str.length() - 1);
                        if (CsvReader.isExisted("\"\"", str)) {
                            str = str.replaceAll("\"\"", "\"");
                        }
                    }
                    if (!"".equals(str)) {
                        listTemp.add(str);
                    }else{
                        listTemp.add(" ");
                    }
                }
                retval.add(listTemp);
                rowReader.getRows(SHEET_NUM, rowNum, listTemp);
                rowNum++;
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }

    /**
     * Regular Expression for CSV parse
     * 
     * @return
     */
    private String getRegExp() {
        final String SPECIAL_CHAR_A = "[^\",\\n  ]";
        final String SPECIAL_CHAR_B = "[^\"" + spaceMark + "\\n]";

        StringBuffer strRegExps = new StringBuffer();
        strRegExps.append("\"((");
        strRegExps.append(SPECIAL_CHAR_A);
        strRegExps.append("*[" + spaceMark + "\\n  ])*(");
        strRegExps.append(SPECIAL_CHAR_A);
        strRegExps.append("*\"{2})*)*");
        strRegExps.append(SPECIAL_CHAR_A);
        strRegExps.append("*\"[  ]*" + spaceMark + "[  ]*");
        strRegExps.append("|");
        strRegExps.append(SPECIAL_CHAR_B);
        strRegExps.append("*[  ]*" + spaceMark + "[  ]*");
        strRegExps.append("|\"((");
        strRegExps.append(SPECIAL_CHAR_A);
        strRegExps.append("*[" + spaceMark + "\\n  ])*(");
        strRegExps.append(SPECIAL_CHAR_A);
        strRegExps.append("*\"{2})*)*");
        strRegExps.append(SPECIAL_CHAR_A);
        strRegExps.append("*\"[  ]*");
        strRegExps.append("|");
        strRegExps.append(SPECIAL_CHAR_B);
        strRegExps.append("*[  ]*");
        return strRegExps.toString();
    }

    /**
     * If argChar is exist in argStr
     * 
     * @param argChar
     * @param argStr
     * @return
     */
    private static boolean isExisted(String argChar, String argStr) {

        boolean blnReturnValue = false;
        if ((argStr.indexOf(argChar) >= 0) && (argStr.indexOf(argChar) <= argStr.length())) {
            blnReturnValue = true;
        }
        return blnReturnValue;
    }

}
相關文章
相關標籤/搜索