数据格式解析教程
作者: 时海 猿王
CSV读写

使用Apache 公共组件Commons CSV 读写CSV文件,具体步骤如下:

1、Maven配置

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.5</version>
</dependency>

2、CSV文件读写案例

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 java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;


public class Test {
    public static void main(String[] args) throws IOException {
        String[] header = new String[]{"uid", "phone"};
        List<Object[]> dataList = new ArrayList<>();
        Object[] data = new Object[]{"001", "13811111111"};
        dataList.add(data);
        data = new Object[]{"002", "13822222222"};
        dataList.add(data);
        String path = "/tmp/test.csv";
        write(path, header, dataList);
        read(path, header);

    }

    /**
     * 读csv文件
     */
    public static void read(String path, String[] header) throws IOException {
        File file = new File(path);
        FileReader fReader = new FileReader(file);
        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator("\n").withHeader(header);
        CSVParser csvParser = new CSVParser(fReader, csvFileFormat);
        List<CSVRecord> csvRecordList = csvParser.getRecords();
        for (CSVRecord item : csvRecordList) {
            for (int i = 0; i < header.length; i++) {
                System.out.print(item.get(header[i]) + ",");
            }
            System.out.println();
        }

        csvParser.close();
    }

    /**
     * 写csv文件
     */
    public static void write(String path, String[] header, List<Object[]> dataList) throws IOException {

        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator("\n").withHeader(header);
        CSVPrinter csvFilePrinter = new CSVPrinter(new OutputStreamWriter(new FileOutputStream(path)), csvFileFormat);
        for (Object[] data : dataList) {
            csvFilePrinter.printRecord(data);
        }
        csvFilePrinter.close();
    }
}


3、参考

http://commons.apache.org/proper/commons-csv/


标签: csv、commons、csvparser、csvformat、import
一个创业中的苦逼程序员
  • 回复
隐藏