java解析CSV文件(getCsvData 解析CSV文件)
首先需要下载opencsv的jar包
<!-- https://mvnrepository.com/artifact/com.opencsv/opencsv --> <dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.6</version> </dependency>
直接上代码
package mocha.framework.hrbase.rest.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.opencsv.CSVReader; import com.opencsv.CSVReaderBuilder; /**. * @Description: TODO(CSV文件解析数据) * @author xiehj * @date 2020年8月18日 上午9:24:56 * @version V1.0 */ public class CsvUtil { /**. * * @param in csv File InputStream * @param charsetName file 的编码方式 */ public static List<String[]> getCsvData(InputStream in, String charsetName) { List<String[]> list = new ArrayList<String[]>(); int i = 0; try (CSVReader csvReader = new CSVReaderBuilder( new BufferedReader( new InputStreamReader( in,charsetName))).build()) { Iterator<String[]> iterator = csvReader.iterator(); while (iterator.hasNext()) { String[] next = iterator.next(); //去除第一行的表头,从第二行开始 if(i >= 1) { list.add(next); } i++; } return list; } catch (Exception e) { System.out.println("CSV文件读取异常"); return list; } } public static void main(String[] args) { //File file = new File("C:\\Users\\A\\Desktop\\1.csv"); String srcPath = "C:\\Users\\A\\Desktop\\导出文件\\20210623170253214_1_10000.csv"; FileInputStream in = null; try { in = new FileInputStream( new File(srcPath)); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String charset = "gbk"; List<String[]> csvData = CsvUtil.getCsvData(in, charset); for (String[] strings : csvData) { for (int i = 0; i < strings.length; i++) { System.out.print(strings[i]+","); } System.out.println(); } } }
文件需要为csv文件,其他的文件是不行的。所以将csv文件奉上。
下载地址:https://files.cnblogs.com/files/blogs/623406/20210623170253214_1_10000.zip
一定要爱着点儿什么,恰似草木对光阴的钟情。