1 需要的jar
<!-- 需要的jar包 -->
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.6</version>
</dependency>
<!-- 使用opencsv必须的jar包 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
<!-- 如果读取带BOM的文件,需要使用下面的包,不使用会出现第一列读不出来 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
2 表头中文映射读取
2.1 java代码
/**
* 使用表头中文映射读取CSV文件,表头为"姓名"、"尺寸"、"描述"
*/
public List<Book> readCsv() {
try {
// 创建输入流
FileInputStream fileInputStream = new FileInputStream(this.hotwordsCsvPath);
// 读取带BOM的CSV文件需要使用BOMInputStream
BOMInputStream bomInputStream = new BOMInputStream(fileInputStream);
// 创建Reader
InputStreamReader inputStreamReader = new InputStreamReader(bomInputStream, StandardCharsets.UTF_8);
CSVReader csvReader = new CSVReaderBuilder(inputStreamReader).build();
// 设置实体映射策略
HeaderColumnNameTranslateMappingStrategy<Book> strategy = new HeaderColumnNameTranslateMappingStrategy<>();
strategy.setType(Book.class);
Map<String, String> columnMapping = new HashMap<>();
columnMapping.put("姓名", "name");
columnMapping.put("尺寸", "height");
columnMapping.put("描述", "desc");
// 设置映射
strategy.setColumnMapping(columnMapping);
// 实体映射
CsvToBeanBuilder<Book> csvToBeanBuilder = new CsvToBeanBuilder<Book>(csvReader);
csvToBeanBuilder.withSeparator(CSVWriter.DEFAULT_SEPARATOR);
csvToBeanBuilder.withQuoteChar(CSVWriter.NO_QUOTE_CHARACTER);
csvToBeanBuilder.withMappingStrategy(strategy);
CsvToBean csvToBean = csvToBeanBuilder.build();
// 解析csv
List list = csvToBean.parse();
System.out.println(list);
} catch (IOException e) {
e.printStackTrace();
} ;
return null;
}
2.2 csv文件
姓名 | 尺寸 | 描述 |
---|
中国 | 0,0.8164938785607375 | 中国人民真精神0 |
中国1 | 0.8979758050541083 | 中国人民真精神1 |
3 简单关系
3.1 java代码
/**
使用默认的方式读取CSV文件,表头为"name"、"height"、"desc";
*/
public List<Book> readCsvSimple(){
try {
// 建立Reader
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("F:\\data\\simple.csv"), StandardCharsets.UTF_8);
CSVReader csvReader = new CSVReaderBuilder(inputStreamReader).build();
// 实体转换
CsvToBeanBuilder<Book> csvToBeanBuilder = new CsvToBeanBuilder<Book>(csvReader);
csvToBeanBuilder.withSeparator(CSVWriter.DEFAULT_SEPARATOR);
csvToBeanBuilder.withQuoteChar(CSVWriter.NO_QUOTE_CHARACTER);
csvToBeanBuilder.withType(Book.class);
CsvToBean csvToBean = csvToBeanBuilder.build();
// 解析列表
List list = csvToBean.parse();
System.out.println(list);
} catch (IOException e) {
e.printStackTrace();
};
return null;
}
3.2 csv文件
tech | weight | desc |
---|
中国 | 0,0.8164938785607375 | 中国人民真精神0 |
中国1 | 0.8979758050541083 | 中国人民真精神1 |
4 实体
/**
Book实体关系
*/
@Data
@NonNull
@NoArgsConstructor
@Component
public class Book {
private String name;
private double height;
private String desc;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
5 使用item读取csv
try {
InputStreamReader reader = new InputStreamReader(new FileInputStream(new File(csvPath)), "UTF-8");
CSVReader csvReader = new CSVReaderBuilder(reader).build();
Iterator<String[]> iterator = csvReader.iterator();
// 如果有数据进行遍历读取
if(iterator.hasNext()){
// 跳过第一行
iterator.next();
// 循环读取数据
while (iterator.hasNext()) {
// 读取一行的数据
List<String> list = Arrays.asList(iterator.next());
// 使用索引读取单元格数据
System.out.println(list[0]);
}
}
return null;
} catch (IOException e) {
System.out.println("Read the csv of "+csvPath+" is error !");
e.printStackTrace();
return false;
}
6 使用OpenCSV写入CSV
// 使用字符串数组写入CSV
public boolean writeCsvArr(){
try {
FileWriter fileWriter = new FileWriter("D:/mybook.csv");
CSVWriter writer = new CSVWriter(fileWriter);
String[] row = new String[]{"name", "height", "desc"};
writer.writeNext(row);
row = new String[]{"zhangsan", "10", "my desc"};
writer.writeNext(row);
writer.close();
fileWriter.close();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
// 含有BOM字符,使用字符串数组写入CSV
public boolean writeCsvArrBom(){
try {
byte [] bs = { (byte)0xEF, (byte)0xBB, (byte)0xBF};
FileOutputStream fileOutputStream = new FileOutputStream("D:/mybook.csv");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
outputStreamWriter.write(new String(bs));
CSVWriter writer = new CSVWriter(outputStreamWriter);
String[] row = new String[]{"name", "height", "desc"};
writer.writeNext(row);
row = new String[]{"zhangsan", "10", "my desc"};
writer.writeNext(row);
writer.close();
outputStreamWriter.close();
fileOutputStream.close();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
// 使用对象列表写入CSV
public boolean writeCsvList(){
try {
Writer writer = new FileWriter("D:/mybook.csv");
StatefulBeanToCsv<Book> beanToCsv = new StatefulBeanToCsvBuilder<Book>(writer).build();
Book book = new Book();
book.setDesc("CSV 11 ");
book.setHeight(11);
book.setName("Read CSV 11");
beanToCsv.write(book);
book = new Book();
book.setDesc("CSV 22");
book.setHeight(22);
book.setName("Read CSV 22");
beanToCsv.write(book);
writer.close();
return true;
} catch (IOException | CsvRequiredFieldEmptyException | CsvDataTypeMismatchException e) {
e.printStackTrace();
}
return false;
}