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();
}
}