jar包下载地址:http://commons.apache.org/proper/commons-csv/,点击Download进行下载!
示例直接看代码吧:
我们首先定义一个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 + ',' + major;
}
}
如下是读写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<Student> 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<String> 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<CSVRecord> 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 周杰伦