public classCsvParser {private BufferedReader bufferedreader = null;private List list = newArrayList();publicCsvParser() {
}public CsvParser(InputStream inStream) throwsException {
InputStreamReader isr= new InputStreamReader(inStream, "GBK");
bufferedreader= newBufferedReader(isr);
String stemp;while ((stemp = readLine()) != null) {
list.add(stemp);
}
}/*** 过滤回车和英文逗号
*
*@return*@throwsException*/
public String readLine() throwsException {
StringBuilder readLine= newStringBuilder();boolean bReadNext = true;while(bReadNext) {//换行符替换
if (readLine.length() > 0) {
readLine.append("\r\n");
}//一行
String strReadLine =bufferedreader.readLine();//readLine is Null
if (strReadLine == null) {return readLine.length() <= 0 ? null: readLine.toString();
}
readLine.append(strReadLine);//如果双引号是奇数的时候继续读取(含有换行时会添加双引号,自带的双引号会转为2个双引号)
if (countChar(readLine.toString(), '"', 0) % 2 == 1) {
bReadNext= true;
}else{
bReadNext= false;
}
}returnreadLine.toString();
}/***计算指定文字的个数。
*
*@paramstr 文字列
*@paramc 文字
*@paramstart 开始位置
*@return个数*/
private int countChar(String str, char c, intstart) {int i = 0;int index =str.indexOf(c, start);return index == -1 ? i : countChar(str, c, index + 1) + 1;
}public List getList() throwsIOException {returnlist;
}/*** csv文件的行数
*
*@return
*/
public intgetRowNum() {returnlist.size();
}/*** 取得指定行的值
*
*@paramindex
*@return
*/
public String getRow(intindex) {if (this.list.size() != 0) {return(String) list.get(index);
}else{return null;
}
}/*** 把CSV文件的一行转换成字符串数组。不指定数组长度。*/
public ListfromCSVLinetoArray(String source) {if (source == null || source.length() == 0) {returnCollections.emptyList();
}int currentPosition = 0;int maxPosition =source.length();int nextComma = 0;
List rtnArray = newArrayList();while (currentPosition
nextComma=nextComma(source, currentPosition);
rtnArray.add(nextToken(source, currentPosition, nextComma));
currentPosition= nextComma + 1;if (currentPosition ==maxPosition) {
rtnArray.add("");
}
}returnrtnArray;
}/*** 查询下一个逗号的位置。
*
*@paramsource 文字列
*@paramst 检索开始位置
*@return下一个逗号的位置。*/
private int nextComma(String source, intst) {int maxPosition =source.length();boolean inquote = false;while (st
}else if ('"' ==ch) {
inquote= !inquote;
}
st++;
}returnst;
}/*** 取得下一个字符串*/
private static String nextToken(String source, int st, intnextComma) {
StringBuilder strb= newStringBuilder();int next =st;while (next
strb.append(ch);
next++;
}
}else{
strb.append(ch);
}
}returnstrb.toString();
}/*** 获取所有行(不含表头)
*
*@return行列表,且每行是一个列表*/
public List>getRowsWithNoHeader() {
List> result = new ArrayList>();for (int i = 1; i < getRowNum(); i++) {
String row=getRow(i);
List oneRow = this.fromCSVLinetoArray(row);if(CollectionUtils.isNotEmpty(oneRow)) {
result.add(oneRow);
}
}returnresult;
}
}