本文最后更新于:June 11, 2023 pm
SpringBoot框架中有两个非常重要的策略:开箱即用和约定优于配置。其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。
目录
逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本)。
CSV文件可以直接用Excel打开,所有在读取和存储时,可以类比Excel。
依赖
| <dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>5.7.1</version> </dependency>
|
读取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @Test void testC() throws Exception { String path = "test.csv"; CSVReader reader = new CSVReader(new FileReader(path)); String[] line; while ((line = reader.readNext()) != null) { String c1 = line[0]; String c2 = line[1]; String c3 = line[2]; System.out.printf("c1=%s c2=%s c3=%s%n",c1,c2,c3); } reader.close(); }
|
存储
将数据存储到指定CSV文件中,会自动生成。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| @Test void readcsv() throws Exception { String path_r = "result.csv"; CSVWriter writer = new CSVWriter(new FileWriter(path_r, true)); String[] temp = new String[3]; temp[0] = "zhang"; temp[1] = "20"; temp[2] = "上海市"; writer.writeNext(temp);
writer.close(); reader.close(); }
|
示例
将test.csv文件里的内容读取到另一新文件中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| @Test void readcsv() throws Exception { String path = "test.csv"; String path_r = "result.csv";
CSVReader reader = new CSVReader(new FileReader(path)); CSVWriter writer = new CSVWriter(new FileWriter(path_r, true));
String[] line; while ((line = reader.readNext()) != null) { writer.writeNext(line); }
writer.close();
reader.close(); }
|
其他
如果想加一个和Excel一样的表头,可以先往CSV文件里面写入一列表头信息,然后再存入数据。稍改上面的示例,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| @Test void readcsv() throws Exception { String path = "test.csv"; String path_r = "result.csv";
CSVReader reader = new CSVReader(new FileReader(path)); CSVWriter writer = new CSVWriter(new FileWriter(path_r, true));
String[] head = new String[3]; head[0] = "name"; head[1] = "age"; head[2] = "address"; writer.writeNext(head);
String[] line; while ((line = reader.readNext()) != null) { writer.writeNext(line); }
writer.close();
reader.close(); }
|