700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Java学习笔记 - Apache Common CSV 的使用总结

Java学习笔记 - Apache Common CSV 的使用总结

时间:2021-11-11 18:02:33

相关推荐

Java学习笔记 - Apache Common CSV 的使用总结

环境依赖

<!--common csv --><!-- /artifact/mons/commons-csv --><dependency><groupId>mons</groupId><artifactId>commons-csv</artifactId><version>1.7</version></dependency>

将数据写入到 CSV文件

// 要读读取的csv文件的 headrprivate final String[] header = new String[]{"deptno", "dname" ,"loc"};private final String FILE_NAME = "H:\\source\\gitRep\\BigdataStudy\\Kylin\\Kylin\\data\\dept.csv";// 注意 : withSkipHeaderRecord 这里要设置跳过 header, 否则会吧 header 当成第一行记录// 如果默认分隔符不是 , 则需要手动设置CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(header).withSkipHeaderRecord()// 设置分隔符.withDelimiter('\t');public void write_csv() throws IOException {// 创建输出流Appendable out = new PrintWriter("dept2.csv");//CSVFormat csvFormat = CSVFormat.newFormat('\t').withHeader(header).withSkipHeaderRecord();// 注意 使用 DEFAULT 创建的CSVFormat对象生成记录可以自动换行,// 如果使用上面的 newFormat 的csvformat 不会自动换行CSVPrinter csvPrinter = CSVFormat.DEFAULT.print(out);/* CSVPrinter csvPrinter = new CSVPrinter(out, csvFormat);*/// 创建 一些记录信息List<String> records = new ArrayList<>();// 部门编号,records.add("RSA001_0121" + "\t" + "产品部" + "\t" + "RSA001");records.add("RSA002_0623" + "\t" + "设计部" + "\t" + "RSA002");records.add("RSA003_0422" + "\t" + "技术部" + "\t" + "RSA003");records.add("RSA004_0903" + "\t" + "运营部" + "\t" + "RSA004");records.add("RSA005_0608" + "\t" + "财务部" + "\t" + "RSA005");// 将数据写入到 文件中for (String record : records) {csvPrinter.printRecord(record);}// 刷写缓冲区csvPrinter.flush();csvPrinter.close();}

从CSV文件中读取数据

// 要读读取的csv文件的 headrprivate final String[] header = new String[]{"deptno", "dname", "loc"};private final String FILE_NAME = "H:\\source\\gitRep\\BigdataStudy\\Kylin\\Kylin\\data\\dept.csv";// 注意 : withSkipHeaderRecord 这里要设置跳过 header, 否则会吧 header 当成第一行记录// 如果默认分隔符不是 , 则需要手动设置CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(header).withSkipHeaderRecord()// 设置分隔符.withDelimiter('\t');public void read_csv() throws IOException {// 将文件转换为 Reader 流Reader in = new FileReader(FILE_NAME);// 解析数据CSVParser parser = csvFormat.parse(in);// 获取记录List<CSVRecord> records = parser.getRecords();// 打印记录for (CSVRecord record : records) {// 获取指定字段的数据String deptno = record.get("deptno");String dname = record.get("dname");String loc = record.get("loc");System.out.println(deptno + "\t" + dname + "\t" + loc);System.out.println(record);}// 关闭流parser.close();in.close();}

参考

Apache Commons CSV User Guide

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。