目录
- Java读取csv文件的两种方式
- 1.CsvReader读取
- 2.BufferedReader读取
java读取csv文件的两种方式
1.CsvReader读取
impjavascriptort com.csvreader.CsvReader; /** * CsvReader 读取 * @param filePath * @return */ public static ArrayList<String> readCsvbyCsvReader(String filePath) { ArrayList<String> strList = null; try { ArrayList<String[]> arrList = new ArrayList<String[]>(); strList = new ArrayList<String>(); CsvReader reader = new CsvReader(filePath, ',', Charset.forName("UTF-8")); while (reader.readRecord()) { // System.out.println(Arrays.asList(reader.getValues())); arrList.add(reader.getValues()); // 按行读取,并把每一行的数据添加到list集合 } reader.close(); System.out.println("读取的行数:" + arrList.size()); // 如果要返回 String[] 类型的 list 集合,则直接返回 arrList // 以下步骤是把 String[] 类型的 list 集合转化为 String 类型的 list 集合 www.devze.com for (int row = 0; row < arrList.size(); row++) { // 组装String字符串 // 如果不知道有多少列,则可再加一个循环 String ele = arrList.get(PXoDVHYqrow)[0] + "," + arrList.get(row)[1] + "," + arrList.get(row)[2] + "," + arrList.get(row)[3] ; System.out.println(ele); strList.add(ele); } } catch (Exception e) { e.printStackTrace(); } return strList; 编程客栈}
CsvReader方式需要引入jar包,pom配置如下
<!--csv文件操作--> <dependency> <groupId>net.sourceforge.javacsv</groupId> <artifactId>javacsv</artifactId> <version>2.0</version> </dependency>
2.BufferedReader读取
/** * BufferedReader 读取 * @param filePath * @return */ public static ArrayList<String> readCsvByBufferedReader(String filePath) { File csv = new File(filePath); csv.setReadable(true); csv.setWritable(true); InputStreamReader isr = null; BufferedReader br = null; try { isr = new InputStreamReader(new FileInputStream(csv), "UTF-8"); br = new BufferedReader(isr); } catch (Exception e) { e.printStackTrace(); } String line = ""; ArrayList<String> records = new ArrayList<>编程客栈(); try { while ((line = br.readLine()) != null) { System.out.println(line); records.add(line); } System.out.println("csv表格读取行数:" + records.size()); } catch (IOException e) { e.printStackTrace(); } return records; }
到此这篇关于Java读取csv文件的两种方式的文章就介绍到这了,更多相关Java读取csv文件内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!
精彩评论