Apache Commons工具类 CSV文件读写

章彬郁
2023-12-01

1 添加依赖

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

2 写入CSV文件

/**
     * 写入csv文件
     * @param headers 列头
     * @param data 数据内容
     * @param filePath 创建的csv文件路径
     */
    public static void writeCsv(String[] headers, List<String[]> data, String filePath) {
        try {
            //初始化csvformat
            //withRecordSeparator 行分隔符,默认就是 \n
            //withDelimiter 字段分隔符
            CSVFormat formator = CSVFormat.DEFAULT
                    .withRecordSeparator("\n")
                    .withDelimiter(',');

            //创建FileWriter对象
            //方式1
            //FileWriter fileWriter=new FileWriter(filePath);

            //方式2
            FileOutputStream fos = new FileOutputStream(filePath);
            OutputStreamWriter fileWriter = new OutputStreamWriter(fos, "UTF-8");

            //创建CSVPrinter对象
            CSVPrinter printer=new CSVPrinter(fileWriter,formator);

            //写入列头数据
            printer.printRecord(headers);

            if(null!=data){
                //循环写入数据
                for(String[] lineData:data){
                    printer.printRecord(lineData);
                }
            }
            //记得添加,不然没有输出
            printer.flush();
            printer.close();
            System.out.println("CSV文件创建成功,文件路径:"+filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


//测试
public static void main(String[] args) throws Exception {
    String[] headers = new String[]{"name","age","address"};

    ArrayList<String[]> data = new ArrayList<>();
    String[] data_1 = new String[]{"wang","21","hei"};
    String[] data_2 = new String[]{"sdf","34","wer"};
    String[] data_3 = new String[]{"seff","56","yui"};
    data.add(data_1);
    data.add(data_2);
    data.add(data_3);

    String csvfilepath="C:/Users/need/Desktop/aaaaa/1.csv";

    writeCsv(headers,data,csvfilepath);
}

3 读取CSV文件

/**读取csv文件
     * @param filePath 文件路径
     * @param headers csv列头
     * @return CSVRecord 列表
     * @throws IOException **/
    public static List<CSVRecord> readCSV(String filePath, String[] headers) throws IOException{

        //创建CSVFormat
        CSVFormat formator = CSVFormat.DEFAULT.withHeader(headers);

        FileReader fileReader=new FileReader(filePath);

        //创建CSVParser对象
        CSVParser parser=new CSVParser(fileReader,formator);

        List<CSVRecord> records=parser.getRecords();

        parser.close();
        fileReader.close();

        return records;
    }

//测试
public static void main(String[] args) throws Exception {
        String[] headers = new String[]{"name","age","address"};
        String csvfilepath="C:/Users/need/Desktop/aaaaa/1.csv";
        List<CSVRecord> csvRecords = readCSV(csvfilepath, headers);
        for (int i = 0; i <csvRecords.size() ; i++) {
            CSVRecord record = csvRecords.get(i);
            System.out.print(record.get("name")+"----"+record.get("age")+"----"+record.get("address"));
            System.out.println();
        }
}

 

 类似资料: