🐓CSV文件是什么
CSV 代表逗号分隔值,是一种非常流行的文件类型。CSV文件用于存储由逗号分隔的信息。文件的每一行都用于表示一个数据记录。
🐓CSV文件的读取
🚩进行CSV文件的解析
private List<CsvRow> getCsvFile(String filePath) { //新建一个CsvReadConfig配置对象 CsvReadConfig csvReadConfig = new CsvReadConfig(); //新建一个CsvReader对象 CsvReader csvRows = new CsvReader(csvReadConfig); //初始化数据 CsvData read = null; read = csvRows.read(new File(filePath), CharsetUtil.CHARSET_UTF_8); //读取数据 List<CsvRow> rows = read.getRows(); return rows; }
🚩Hutool包中的CsvReadConfig配置类(可以动态设置开始和结束)
import java.io.Serializable; public class CsvReadConfig extends CsvConfig<CsvReadConfig> implements Serializable { private static final long serialVersionUID = 5396453565371560052L; protected long headerLineNo = -1L; protected boolean skipEmptyRows = true; protected boolean errorOnDifferentFieldCount; protected long beginLineNo; protected long endLineNo = 9223372036854775806L; protected boolean trimField; public CsvReadConfig() { } public static CsvReadConfig defaultConfig() { return new CsvReadConfig(); } public CsvReadConfig setContainsHeader(boolean containsHeader) { return this.setHeaderLineNo(containsHeader ? this.beginLineNo : -1L); } public CsvReadConfig setHeaderLineNo(long headerLineNo) { this.headerLineNo = headerLineNo; return this; } public CsvReadConfig setSkipEmptyRows(boolean skipEmptyRows) { this.skipEmptyRows = skipEmptyRows; return this; } public CsvReadConfig setErrorOnDifferentFieldCount(boolean errorOnDifferentFieldCount) { this.errorOnDifferentFieldCount = errorOnDifferentFieldCount; return this; } public CsvReadConfig setBeginLineNo(long beginLineNo) { this.beginLineNo = beginLineNo; return this; } public CsvReadConfig setEndLineNo(long endLineNo) { this.endLineNo = endLineNo; return this; } public CsvReadConfig setTrimField(boolean trimField) { this.trimField = trimField; return this; } }