參考github大神源碼 總結一下最簡單的工具類記錄一下
/** * @description CSV文件讀取和輸出 工具類.<br/> * @author michael * @date 2019/05/16 * @version Copyright (c) 2019, michael.xie@adsnova.cn All Rights Reserved. */ public class CSVFileUtil { private static final Logger LOGGER = LoggerFactory.getLogger(CSVFileUtil.class); public static final String ENCODE = "UTF-8"; /** * readCsv:根據路徑讀取CSV文件.<br/> * * @param csvFilePath * @return */ public static List<String[]> readCsv(String csvFilePath) { List<String[]> csvList = new ArrayList<String[]>(); 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()); } return csvList; } /** * readCsv:根據數據流讀取CSV文件.<br/> * * @param csvIs * @return */ public static List<String[]> readCsv(InputStream csvIs) { List<String[]> csvList = new ArrayList<String[]>(); try { CsvReader reader = new CsvReader(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()); } return csvList; } /** * writeCsv:把內容寫入到文件中.<br/> * * @param csvFilePath * @param contents */ public static void writeCsv(String csvFilePath, List<String[]> contents) { 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:把內容寫到輸出流.<br/> * * @param ou * @param list */ public static void writeCsv(OutputStream ou, List<String[]> list) { 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(); } } } }