Content Table

Java 读写 CSV

Java-csv

使用 Javacsv 读写 CSV,如果 csv 文件中有空行,不会报错,比 commons-csv 好用,性能也更好一些。

Gradle 依赖

1
compile 'net.sourceforge.javacsv:javacsv:2.0'

读取 CSV:

1
2
3
4
5
6
7
8
9
10
import com.csvreader.CsvReader;

// CsvReader csvReader = new CsvReader("/Users/Biao/Desktop/20191017.csv", ',', new GB18030());
CsvReader csvReader = new CsvReader("/Users/Biao/Desktop/20191017.csv", ',', StandardCharsets.UTF_8);
csvReader.readHeaders();

while (csvReader.readRecord()) {
String name = csvReader.get(0); // csvReader.get("name");
...
}

写入 CSV:

1
2
3
4
5
6
7
8
9
10
11
12
CsvWriter writer = new CsvWriter("/Users/Biao/Desktop/test.csv", ',', StandardCharsets.UTF_8);

// 写入 CSV Headers
writer.writeRecord(new String[] { "账号", "类型", "角色", "时间", "内容" });

// 写入 CSV 内容
writer.writeRecord(new String[] { "1", "2", "3", "4", "5" });
writer.writeRecord(new String[] { "1", "2", "3", "4", "5" });
writer.writeRecord(new String[] { "1", "2", "3", "4", "5" });

// 结束写入,保存到文件
writer.close();

Commons-csv

使用 Apache 的 commons-csv 读写 CSV,如果 csv 文件中有空行 (只允许末尾一个空行),会报错。

Gradle 依赖

1
'org.apache.commons:commons-csv:1.2'

test.csv

CSV 文件的第一行可以是列名,也可以没有。

1
2
3
4
5
x,y,ex,ey
1.1,1.2,1.3,1.4
2.1,2.2,2.3,2.4
3.1,3.2,3.3,3.4
4.1,4.2,4.3,4.4

CsvReader.java

  • 读取带有列名的 CSV 使用 CSVFormat.EXCEL.withHeader().parse(reader)
  • 读取不带列名的 CSV 使用 CSVFormat.EXCEL.parse(reader)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class CsvReader {
public static void main(String[] args) throws Exception {
InputStream in = CsvReader.class.getClassLoader().getResourceAsStream("test.csv");

try (Reader reader = new InputStreamReader(Objects.requireNonNull(in))) {
Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(reader);

for (CSVRecord record : records) {
System.out.printf("[x: %s, y: %s]\n", record.get("x"), record.get("y"));
}
} catch (IOException ignore) {}
}
}

输出

1
2
3
4
[x: 1.1, y: 1.2]
[x: 2.1, y: 2.2]
[x: 3.1, y: 3.2]
[x: 4.1, y: 4.2]

CsvWriter.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import java.io.IOException;

public class CsvWriter {
public static void main(String[] args) throws IOException {
// Create the CSVFormat object with "\n" as a record delimiter
StringBuilder result = new StringBuilder();
CSVFormat csvFormat = CSVFormat.DEFAULT.withRecordSeparator("\n");
CSVPrinter csvPrinter = new CSVPrinter(result, csvFormat);

csvPrinter.printRecord("ID", "username", "password");
csvPrinter.printRecord("1", "Alice", "Passw0rd");
csvPrinter.printRecord("2", "Bob", "123456");
csvPrinter.printRecord("3", "John", "Aloha");
csvPrinter.close();

System.out.println(result);
}
}

输出

1
2
3
4
ID,username,password
1,Alice,Passw0rd
2,Bob,123456
3,John,Aloha

参考