读取csv文件
实现代码:
/**
* com.csvreader.CsvReader 读取 csv文件
* @param filePath
* @return
* @throws IOException
*/
private static List<String []> csvReader(String filePath) throws IOException{
if (StringUtils.isEmpty(filePath)) {
System.out.println("文件路径不可为空!");
return null;
}
if (!filePath.matches("^.+\\.(?i)(csv)$")) {
System.out.println("此文件不是csv文件!");
return null;
}
List<String []> list = new ArrayList<String []>();
CsvReader csvReader = new CsvReader(filePath, ',', Charset.forName("GBK"));
csvReader.readHeaders();//跳过表头,如果需要表头,注释即可
while (csvReader.readRecord()) {//逐行读取除表头外的数据
list.add(csvReader.getValues());
}
//关闭资源
csvReader.close();
return list;
}
验证:
public static void main(String[] args) {
String pFile = "D:/Users/1.csv";
try {
List<String []> list = csvReader(pFile);
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.get(i).length; j++) {
System.out.print(list.get(i)[j] + "|");
}
System.out.println();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}