使用Apache Common CSV读写CSV文件

网友投稿 1195 2022-09-06

使用Apache Common CSV读写CSV文件

使用Apache Common CSV读写CSV文件

示例直接看代码吧:

我们首先定义一个Student的Bean:

class Student { public Student() { } public Student(String id, String name, String gender, String major) { super(); this.id = id; this.name = name; this.gender = gender; this.major = major; } private String id; private String name; private String gender; private String major; public String getID() { return id; } public void setID(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } @Override public String toString() { return id + ',' + name + ',' + gender + ','

如下是读写CSV的代码:

import java.io.FileReader;import java.io.FileWriter;import java.io.Reader;import java.io.Writer;import java.util.ArrayList;import java.util.List;import org.apache.commons.csv.CSVFormat;import org.apache.commons.csv.CSVPrinter;import org.apache.commons.csv.CSVRecord;public class CSVDemo { public static void main(String[] arg) { final String[] FILE_HEADER = {"ID","Name","Gender","Major"}; final String FILE_NAME = "student.csv"; Student stuTZY = new Student("001", "谭振宇", "男", "GIS"); Student stuZJL = new Student("002", "周杰伦", "男", "音乐"); List students = new ArrayList<>(); students.add(stuTZY); students.add(stuZJL); // 这里显式地配置一下CSV文件的Header,然后设置跳过Header(要不然读的时候会把头也当成一条记录) CSVFormat format = CSVFormat.DEFAULT.withHeader(FILE_HEADER).withSkipHeaderRecord(); // 这是写入CSV的代码 try(Writer out = new FileWriter(FILE_NAME); CSVPrinter printer = new CSVPrinter(out, format)) { for (Student student : students) { List records = new ArrayList<>(); records.add(student.getID()); records.add(student.getName()); records.add(student.getGender()); records.add(student.getMajor()); printer.printRecord(records); } } catch (Exception e) { e.printStackTrace(); } // 这是从上面写入的文件中读出数据的代码 try(Reader in = new FileReader(FILE_NAME)) { Iterable records = format.parse(in); String strID; String strName; for (CSVRecord record : records) { strID = record.get("ID"); strName = record.get("Name"); System.out.println(strID + " " + strName); } } catch (Exception e) { e.printStackTrace();

输入结果:

001 谭振宇002 周杰伦

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:安装Windows和Linux双系统需要注意的一些问题
下一篇:SQL Server调优系列进阶篇(如何索引调优)(sql语句)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~