import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CsvUtil {
/**
* 读取CSV格式的文档数据
* @param filePath CSV格式的文件路劲
* @return dataList csv数据读取放入二维list中。
*/
public static List<List<String>> readCSVFileData(String filePath){
BufferedReader reader=null;
List<List<String>> dataList=new ArrayList<>();
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
}catch(FileNotFoundException | UnsupportedEncodingException e){
e.printStackTrace();
}
try{
String line=null;
int lineNum =0;
while ((line=reader.readLine())!=null){
if (lineNum != 0) {
//(1)内容不存在逗号
// String aa[]=line.split(",");
// List<String> cellList= Arrays.asList(aa);
// //System.out.println(cellList);
// dataList.add(cellList);
//(1)内容可能存在逗号,且存在“”英文双引号
String str;
line += ",";
Pattern pCells = Pattern.compile("(\"[^\"]*(\"{2})*[^\"]*\")*[^,]*,");
Matcher mCells = pCells.matcher(line);
List<String> cells = new LinkedList();//每行记录一个list
//读取每个单元格
while (mCells.find()) {
str = mCells.group();
str = str.replaceAll("(?sm)\"?([^\"]*(\"{2})*[^\"]*)\"?.*,", "$1");
str = str.replaceAll("(?sm)(\"(\"))", "$2");
cells.add(str);
}
dataList.add(cells);
}
lineNum++;
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (reader != null) {
//释放资源
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return dataList;
}
/**
* 写入数据到csv格式的文档
* @param filePath CSV格式的文件路劲
* @param dataList 需要写入的数据
* @return dataList csv数据读取放入二维list中。
*/
public static void writeCSVFileData(String filePath,List<List<String>> dataList){
BufferedWriter bw=null;
try {
bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true), "GBK"));
for(int i = 0; i<dataList.size(); i++) {
bw.write(dataList.get(i).get(0)+","+dataList.get(i).get(1));
bw.newLine();
}
} catch (FileNotFoundException e) {
//e.printStackTrace();
System.out.println(e);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (bw != null) {
bw.flush();
//释放资源
bw.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}