Comma-Separated Values(CSV), 因分隔符没有严格指定规范标准,可以使用逗号,也可以使用其他字符(如制表符\t、分号;等),所以CSV也称为 逗号分隔值或者字符分隔值。csv文件是使用纯文本来存储表格数据(即只能存储文本,不能存储二进制数据)。CSV因没有严格的规范,所以变异的形式比较多。
组成:
规则:
示例:
"ID,Name,Age,Birthday,\n1,zhangsan,20,1990-08-08,\n2,lisi,21,1990-08-09,\n"
.csv文件可以被excel软件打开,csv只能用于存储纯文本内容,excel不仅支持纯文本内容还支持二进制数据,可以看做csv是excel的轻量级简单版的实现,excel比csv更加强大,csv文件一般用于表格数据的传输。
官网:http://opencsv.sourceforge.net/
maven:https://mvnrepository.com/artifact/com.opencsv/opencsv 目前最新版本4.0,更新比较频繁,4.0版本还不够成熟。
支持注解(根据名称或者位置)
支持自定义转换器AbstractBeanField
支持跳跃行skipLine和数据过滤Filter
注解:
CSVWriter
public CSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd);
public void writeAll(List allLines);
public void writeNext(String[] nextLine);
protected void writeColumnNames(ResultSet rs);
public void flush();
public void close();
CSVReader
public CSVReader(Reader reader, char separator, char quotechar, char escape, int line, boolean strictQuotes, boolean ignoreLeadingWhiteSpace);
public String[] readNext();
public List readAll();
public void close();
Strategy
ColumnPositionMappingStrategy
HeaderColumnNameMappingStrategy
HeaderColumnNameTranslateMappingStrategy
自定义的符号:
// CSVWriter 写
@Test
public void testWriteByStringArray() throws Exception{
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("D:\\test.csv"), Charset.forName("UTF-8"));
CSVWriter csvWriter = new CSVWriter(out, ',');
String[] record0 = {"id", "name", "age", "birthday"};
csvWriter.writeNext(record0);
String[] record1 = {"1", "张三", "20", "1990-08-08"};
String[] record2 = {"2", "lisi", "21", "1991-08-08"};
String[] record3 = {"3", "wangwu", "22", "1992-08-08"};
List<String[]> allLines = new ArrayList<String[]>();
allLines.add(record1);
allLines.add(record2);
allLines.add(record3);
csvWriter.writeAll(allLines);
csvWriter.close();
}
// CSVReader 读
@Test
public void testRead() throws Exception{
InputStreamReader in = new InputStreamReader(new FileInputStream("D:\\test.csv"), Charset.forName("UTF-8"));
CSVReader reader = new CSVReader(in, ',');
List allRecords = reader.readAll();
for (String[] records : allRecords) {
for (String filed : records) {
System.out.print(filed + " ");
}
System.out.println();
}
reader.close();
}
package com.mengday.csv;
import com.opencsv.bean.*;
import com.opencsv.bean.customconverter.ConvertSplitOnWhitespace;
import java.util.Date;
import java.util.List;
public class User {
@CsvBindByName(required = true)
private Long id;
@CsvBindByName(column = "User Name")
private String name;
private int age;
@CsvBindByName
@CsvDate("yyyy-MM-dd hh:mm:ss")
private Date birthday;
@CsvCustomBindByName(converter = ConvertSplitOnWhitespace.class)
private List tags;
@CsvBindByName
private boolean vip;
public User(){
}
public User(Long id, String name, int age, Date birthday, List tags, boolean vip) {
this.id = id;
this.name = name;
this.age = age;
this.birthday = birthday;
this.tags = tags;
this.vip = vip;
}
// Getter && Setter && toString()
}
@Test
public void testCSVWriteByAnnotation() throws Exception{
List users = new ArrayList();
users.add(new User(1L, "张'三'", 20, new Date(), Arrays.asList("eat", "drink", "girl"), true));
users.add(new User(2L, "李,四", 21, new Date(), Arrays.asList("mm", "money"), false));
users.add(new User(3L, "王\n五", 22, new Date(), Arrays.asList("girl", "$"), true));
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream("D:\\test.csv"), Charset.forName("UTF-8"));
StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer).withSeparator('\t').withQuotechar('\'').build();
beanToCsv.write(users);
writer.close();
}
@Test
public void testCSVReadByAnnotation() throws Exception{
InputStreamReader in = new InputStreamReader(new FileInputStream("D:\\test.csv"), Charset.forName("UTF-8"));
HeaderColumnNameMappingStrategy strategy = new HeaderColumnNameMappingStrategy();
strategy.setType(User.class);
CsvToBean csvToBean = new CsvToBeanBuilder(in).withSeparator('\t').withQuoteChar('\'').withMappingStrategy(strategy).build();
List users = csvToBean.parse();
for(User user: users) {
System.out.println(user);
}
}