java解析csv文件工具类_CSVFileUtil 读取写入CSV文件简单工具类

/*** @description CSV文件读取和输出 工具类.

*@authormichael

* @date 2019/05/16

*@versionCopyright (c) 2019, michael.xie@adsnova.cn All Rights Reserved.*/

public classCSVFileUtil {private static final Logger LOGGER = LoggerFactory.getLogger(CSVFileUtil.class);public static final String ENCODE = "UTF-8";/*** readCsv:根据路径读取CSV文件.

*

*@paramcsvFilePath

*@return

*/

public static ListreadCsv(String csvFilePath) {

List csvList = new ArrayList();try{

CsvReader reader= new CsvReader(csvFilePath, ',', Charset.forName(ENCODE));/**跳过表头 如果需要表头的话,不要写这句*/reader.readHeaders();while(reader.readRecord()) {

csvList.add(reader.getValues());

}

reader.close();

}catch(FileNotFoundException e) {

e.printStackTrace();

LOGGER.error("read csv file error. : {}", e.getLocalizedMessage());

}catch(IOException e) {

e.printStackTrace();

LOGGER.error("read csv file error. : {}", e.getLocalizedMessage());

}returncsvList;

}/*** readCsv:根据数据流读取CSV文件.

*

*@paramcsvIs

*@return

*/

public static ListreadCsv(InputStream csvIs) {

List csvList = new ArrayList();try{

CsvReader reader= newCsvReader(csvIs, Charset.forName(ENCODE));/**跳过表头 如果需要表头的话,不需要写这句*/reader.readHeaders();while(reader.readRecord()) {

csvList.add(reader.getValues());

}

reader.close();

}catch(FileNotFoundException e) {

e.printStackTrace();

LOGGER.error("read csv inputStream error. : {}", e.getLocalizedMessage());

}catch(IOException e) {

e.printStackTrace();

LOGGER.error("read csv inputStream error. : {}", e.getLocalizedMessage());

}returncsvList;

}/*** writeCsv:把内容写入到文件中.

*

*@paramcsvFilePath

*@paramcontents*/

public static void writeCsv(String csvFilePath, Listcontents) {try{

CsvWriter wr= new CsvWriter(csvFilePath, ',', Charset.forName(ENCODE));for (int i = 0; i < contents.size(); i++) {

wr.writeRecord(contents.get(i));

}

wr.close();

}catch(IOException e) {

e.printStackTrace();

LOGGER.error("write csv file error. : {}", e.getLocalizedMessage());

}

}/***

* writeCsv:把内容写到输出流.

*

*@paramou

*@paramlist*/

public static void writeCsv(OutputStream ou, Listlist) {

CsvWriter cw= null;try{

cw= new CsvWriter(ou, ',', Charset.forName(ENCODE));for(String[] s : list) {

cw.writeRecord(s);

}//在文件中增加BOM,该处的byte[] 可以针对不同编码进行修改

ou.write(new byte[] {(byte)0xEF, (byte)0xBB, (byte)0xBF});

cw.flush();

}catch(IOException e) {

e.printStackTrace();

LOGGER.error("write csv outputStream error. : {}", e.getLocalizedMessage());

}finally{if (null !=cw) {

cw.close();

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值