Bootstrap

java读取csv文件 逗号_Java读取CSV文件(CSV文件数据内容包含逗号处理)

/**

* @param srcPath  csv文件路径

*/

private void readCSVFileData(String srcPath) {

BufferedReader reader = null;

String line = null;

try {

reader = new BufferedReader(new FileReader(srcPath));

} catch (FileNotFoundException e) {

logger.error("[读取CSV文件,插入数据时,读取文件异常]");

e.printStackTrace();

}

String[] fieldsArr = null;

int lineNum = 0;

int insertResult = 0;

TableInfo tableInfo = new TableInfo();

tableInfo.setTableName(tableName);

try {

List listField;

while ((line = reader.readLine()) != null) {

if (lineNum == 0) {

//表头信息

fieldsArr = line.split(",");

} else {

//数据信息

listField = new ArrayList<>();

String str;

line += ",";

Pattern pCells = Pattern

.compile("(\"[^\"]*(\"{2})*[^\"]*\")*[^,]*,");

Matcher mCells = pCells.matcher(line);

List cells = new LinkedList();//每行记录一个list

//读取每个单元格

while (mCells.find()) {

str = mCells.group();

str = str.replaceAll(

"(?sm)\"?([^\"]*(\"{2})*[^\"]*)\"?.*,", "$1");

str = str.replaceAll("(?sm)(\"(\"))", "$2");

cells.add(str);

}

//从第2行起的数据信息list

listField.add(cells);

}

lineNum++;

}

} catch (Exception e) {

e.printStackTrace();

}

}

;