import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern; /**
* CsvParser
* 此类参考了网上方案,在此表示感谢
* 2013-12-10 21:43:48
*/
public class CsvParser{
// Saved input CSV file pathname
private String inputCsvFile; // Space mark , ; : etc.
private String spaceMark=","; /**
* Contructor
* @param inputCsvFile
*/
public CsvParser(String inputCsvFile,String spaceMark){
this.inputCsvFile=inputCsvFile;
this.spaceMark=spaceMark;
} /**
* Contructor
* @param inputCsvFile
*/
public CsvParser(String inputCsvFile){
this.inputCsvFile=inputCsvFile;
this.spaceMark=",";
} /**
* Get parsed array from CSV file
* @return
*/
public Object[] getParsedArray() throws Exception{
List<List<String>> retval=new ArrayList<List<String>>(); String regExp = getRegExp();
BufferedReader in = new BufferedReader(new FileReader(this.inputCsvFile));
String strLine;
String str = ""; while ((strLine = in.readLine()) != null) {
Pattern pattern = Pattern.compile(regExp);
Matcher matcher = pattern.matcher(strLine);
List<String> 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 (CsvParser.isExisted("\"\"", str))
{
str = str.replaceAll("\"\"", "\"");
}
} if (!"".equals(str))
{
listTemp.add(str);
}
} // Add to retval
retval.add(listTemp);
}
in.close(); return retval.toArray();
} /**
* 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;
} /**
* Test
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception{
CsvParser parser=new CsvParser("C:\\Users\\IBM_ADMIN\\Desktop\\Test CSV Files\\dummydata_not quoted_1.csv");
//CsvParser parser=new CsvParser("C:\\Users\\IBM_ADMIN\\Desktop\\Test CSV Files\\dummydata_not quoted_2.csv");
//CsvParser parser=new CsvParser("C:\\Users\\IBM_ADMIN\\Desktop\\Test CSV Files\\dummydata_quoted.csv");
//CsvParser parser=new CsvParser("C:\\Users\\IBM_ADMIN\\Desktop\\Test CSV Files\\dummydata_quoted_2.csv"); //CsvParser parser=new CsvParser("C:\\Users\\IBM_ADMIN\\Desktop\\Test CSV Files\\dummydata_1.csv",";");
//CsvParser parser=new CsvParser("C:\\Users\\IBM_ADMIN\\Desktop\\Test CSV Files\\dummydata_2.csv",":"); Object[] arr=parser.getParsedArray();
//System.out.println(arr); for(Object obj:arr){
System.out.print("["); List<String> ls=(List<String>)obj; for(String item:ls){
System.out.println(item+",");
} System.out.println("],");
}
}
}

解析CSV文件:

Column1,Column2,Column3,Column4,Column5
Roderick Manuel,2013-02-21,59 E Brillhart Ave,67526,branch damage other impulse
Lashonda Frank,2012-11-21,418 US Hwy 100,22609,fowl house
Holly Silva,2013-09-15,16345 Old Jacksboro Hwy,13140,art sand colour tray boiling
Martin Forbes,2013-04-28,69 Spr 33,91656,bag point necessary country
Josefa Berry,2008-08-21,125 Hwy' 84 E,12604,Sort industry married safe shirt
Allyson Green,2004-11-11,425 Ranch Rd 587,35059,mother political
Tim Hopkins,2005-03-17,9559 I- 820,83598,crush. surprise station' distance from
Olen Abbott,2009-02-17,2249 Westwood Dr N,15575,acid
Ana Fowler,2011-02-19,22 State Loop 426,13409,memory poor farm adjustment
Minerva House,2009-02-18,57151 Collett Rd,45782,dry summer

将解析完得到的数组输出如下:

[Column1,
Column2,
Column3,
Column4,
Column5,
],
[Roderick Manuel,
2013-02-21,
59 E Brillhart Ave,
67526,
branch damage other impulse,
],
[Lashonda Frank,
2012-11-21,
418 US Hwy 100,
22609,
fowl house,
],
[Holly Silva,
2013-09-15,
16345 Old Jacksboro Hwy,
13140,
art sand colour tray boiling,
],
[Martin Forbes,
2013-04-28,
69 Spr 33,
91656,
bag point necessary country,
],
[Josefa Berry,
2008-08-21,
125 Hwy' 84 E,
12604,
Sort industry married safe shirt,
],
[Allyson Green,
2004-11-11,
425 Ranch Rd 587,
35059,
mother political,
],
[Tim Hopkins,
2005-03-17,
9559 I- 820,
83598,
crush. surprise station' distance from,
],
[Olen Abbott,
2009-02-17,
2249 Westwood Dr N,
15575,
acid,
],
[Ana Fowler,
2011-02-19,
22 State Loop 426,
13409,
memory poor farm adjustment,
],
[Minerva House,
2009-02-18,
57151 Collett Rd,
45782,
dry summer,
],

一个CSV文件解析类的更多相关文章

  1. 【Java/csv】一个CSV文件解析类(转载)

    /*下文写得不错,值得学习**/ import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayLis ...

  2. java csv 文件 操作类

    一个CSV文件操作类,功能比较齐全: package tool; import java.io.BufferedReader; import java.io.BufferedWriter; impor ...

  3. 【转载】 C#工具类:Csv文件转换类

    CSV是逗号分隔值格式的文件,其文件以纯文本形式存储表格数据(数字和文本).CSV文件由任意数目的记录组成,记录间以某种换行符分隔:每条记录由字段组成,字段间的分隔符是其它字符或字符串,最常见的是逗号 ...

  4. CSV文件读取类

    最近项目中,经常需要读取Csv文件.基本步骤是: (1)按行读取 (2)然后将一行数据按逗号,分割为字符串数组 (3)将各列字符串转换成相应类型的数据 ,如int double类型 写了一个简单的Cs ...

  5. CSV文件解析

    CSV(逗号分隔值文件格式)        逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和 ...

  6. 自己用的框架写了一个PHP模版解析类

    <?php if(!defined('IS_HEARTPHP')) exit('Access Denied'); /** * template.class.php 模板解析类 * * @copy ...

  7. CSV文件解析工具

    package com.common.util; import java.io.BufferedReader; import java.io.FileInputStream; import java. ...

  8. php上传excle文件,csv文件解析为二维数组

    解析上传的CSV文件不是什么难事,直接读取转成你想要的数组样子就OK了. public function putStoreStockIn ($filePath = '') { $file = fope ...

  9. Unity C# CSV文件解析与加载(已更新移动端处理方式)

    在游戏开发过程中,经常要用到Excel编辑各类数据,如果可以直接用Excel支持的文件格式来读取数据,修改将非常便捷. Excel支持导出CSV类型的文件,这类文件不仅可以用Excel直接打开修改,即 ...

随机推荐

  1. pyplot图像组件

    pyplot图像组件 ax子对象的组件内容 Title 图表标题 plt.title() Axis 坐标范围,x轴,y轴 plt.axis() label 坐标轴标注 plt.xlabel() plt ...

  2. java程序运行时间

    方法一 long startTime = System.currentTimeMillis(); //获取开始时间 doSomething(); //测试的代码段 long endTime = Sys ...

  3. webpack 构建同时适用于手机和电脑的调试服务器

    plugins plugins: [ new HtmlWebpackPlugin({ // 使用模板同时生成 pc.html和mobile.html title: 'pc', filename: 'p ...

  4. HTTP Error 500.0 - Internal Server Error错误代码0x80070002

    案例研究:AspNetInitClrHostFailureModule中的“HTTP错误500.0 - 内部服务器错误” 症状 当用户访问在Windows Server 2008 R2计算机上运行的A ...

  5. jQuery实现锚点滑动定位

    go=function(index){ var top = $('#caseNewGuide' + index).offset().top; $('html, body').animate({ scr ...

  6. 信息: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path:

    问题信息详细: 信息: The APR based Apache Tomcat Native library which allows optimal performance in productio ...

  7. 关于Python的OSError和IOError

    参考:http://stackoverflow.com/questions/29347790/difference-between-ioerror-and-oserror 在3.x版本已经移除,剩下O ...

  8. Nginx配置杂记(转)

    转至:http://www.cnblogs.com/kuangke/p/5619400.html Nginx是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP代理服务器,相较 ...

  9. css3阴影效果

    http://blog.csdn.net/freshlover/article/details/7610269

  10. vue cli+axios踩坑记录+拦截器使用,代理跨域proxy(更新)

    16319 1.首先axios不支持vue.use()方式声明使用,看了所有近乎相同的axios文档都没有提到这一点建议方式 在main.js中如下声明使用 import axios from 'ax ...