commons-csv
是Apache开源组织提供的用于读写CSV文件的工具包,比较简单,直接上代码:
package com.gujin.csv;
import java.io.FileReader;
import java.io.PrintWriter;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.junit.Test;
public class CSVTest
{
@Test
public void write() throws Exception
{
Appendable out = new PrintWriter("file.csv");
CSVPrinter printer = CSVFormat.DEFAULT.withHeader("userId", "userName")
.print(out);
for (int i = 0; i < 10; i++)
{
printer.printRecord("userId" + i, "userName" + i);
}
printer.flush();
printer.close();
}
@Test
public void read() throws Exception
{
FileReader reader = new FileReader("file.csv");
CSVParser parser = CSVFormat.DEFAULT.withHeader("userId", "userName")
.parse(reader);
for (CSVRecord record : parser)
{
System.out
.println(record.get("userId") + ":" + record.get("userName"));
}
reader.close();
}
}
- 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
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 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
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41