opencsv
介绍
java中读写csv文件的库
依赖
<!-- https://mvnrepository.com/artifact/com.opencsv/opencsv -->
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.5</version>
</dependency>
帮助文档
http://opencsv.sourceforge.net/
例子
(列表<数组>)写入
public void test_write_csv() {
String myPath ="data_"+System.currentTimeMillis() + ".csv";
String str = "a,b,c,d,e,f,g,h\n1,2,3,4,5,6,7,8";
String[] split = str.split("\n");
List<String[]> data = new ArrayList<>();
for (int i = 0; i < split.length; i++) {
data.add(split[i].split(","));
}
try (CSVWriter writer = new CSVWriter(Files.newBufferedWriter(Paths.get(myPath), StandardCharsets.UTF_8),
CSVWriter.DEFAULT_SEPARATOR,
CSVWriter.NO_QUOTE_CHARACTER,
CSVWriter.NO_ESCAPE_CHARACTER,
CSVWriter.DEFAULT_LINE_END)) {
//写数据到文件
writer.writeAll(data);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
读出(到列表<数组>中)
public void test_read_csv() throws IOException {
String myPath ="D:\\projects\\tmp\\ume-plugins-REM-RNC\\NONE\\V1\\plugins\\cli\\modules\\rnccli\\1656414764057.csv";
CSVReader reader = new CSVReader(new FileReader(myPath));
List<String[]> list = reader.readAll();
for (String[] item : list) {
System.out.println(Arrays.asList(item));
}
注意点
- 以逗号为分隔符,数据中有逗号,会错位,解决方法,数据加上双引号便可区分