1.pom.xml引入jar包
<!--csv--> <dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.4</version> </dependency>
2.使用IO流解析,转化数组形式
/** * <b>将csv文件通过IO流解析,转化数组形式的集合<b> * * @param fileName 文件(路径+csv文件名) */ public static List<String[]> csv(String fileName) { List<String[]> csvList = new ArrayList<String[]>(); if (null != in) { try { InputStreamReader is = new InputStreamReader(new FileInputStream(fileName),"gbk"); CSVParser csvParser = new CSVParserBuilder().build(); CSVReader reader = new CSVReaderBuilder(is).withCSVParser(csvParser).build(); csvList = reader.readAll(); }catch (UnsupportedEncodingException e){ e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } } return csvList; }
3.调用测试main
public static void main(String[] args) throws IOException{ List<String[]> strings = csv("路径+csv文件名"); System.out.println("读取成功"); for (String[] csvs:strings) { for (String s:csvs) { System.out.println(s); } } }