记录一下 csv 文件上传下载至 oss 工具类

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import com.opencsv.CSVWriter;
import com.opencsv.bean.*;
import lombok.extern.slf4j.Slf4j;


/**
 * CsvUtil
 * 
 * @author xiaofeifei
 * @date 2020-06-12 20:45
 */
@Slf4j
public final class CsvUtil {

    /**
     * 解析csv文件并转成bean
     * 
     * @param in csv文件
     * @param clazz 类
     * @param <T> 泛型
     * @return 泛型bean集合
     */
    public static <T> List<T> getCsvData(InputStream in, Class<T> clazz) {
        InputStreamReader reader = null;
        try {
            reader = new InputStreamReader(CsvUtil.getInputStream(in), StandardCharsets.UTF_8);
        } catch (IOException e) {
           log.error(e.getMessage(), e);
            SystemException.doThrow("解析csv文件异常");
        }

        HeaderColumnNameMappingStrategy<T> mappingStrategy = new HeaderColumnNameMappingStrategy<>();
        mappingStrategy.setType(clazz);
        CsvToBean<T> build = new CsvToBeanBuilder<T>(reader).withMappingStrategy(mappingStrategy).withSeparator(',').build();
        return build.parse();
    }

    /**
     * 读取流中前面的字符,看是否有bom,如果有bom,将bom头先读掉丢弃
     *  (opencsv 按列名获取bean对象,第一列缺失的情况)
     *  InputStreamReader is = new InputStreamReader(
     *  CsvUtil.getInputStream(new  FileInputStream(fileName)), "utf-8");
     * @param in
     * @return
     * @throws IOException
     */
    public static InputStream getInputStream(InputStream in) throws IOException {

        PushbackInputStream testin = new PushbackInputStream(in);
        int ch = testin.read();
        if (ch != 0xEF) {
            testin.unread(ch);
        } else if ((ch = testin.read()) != 0xBB) {
            testin.unread(ch);
            testin.unread(0xef);
        } else if ((ch = testin.read()) != 0xBF) {
            throw new IOException("错误的UTF-8格式文件");
        } else {
        }
        return testin;
    }

    /**
     * 将前台传递的数据生成csv文件
     * @param exportResults
     * @param header
     */
    public static<T> InputStream upload(List<T> exportResults, File tempFile, String[] header) {
        // 创建临时文件
        CSVWriter csvWriter = null;
        Writer writer = null;
        try {
            writer = new FileWriter(tempFile);
            // 写表头
            csvWriter = new CSVWriter(writer, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END);
            csvWriter.writeNext(header);
            //写内容
            StatefulBeanToCsv<T> beanToCsv = new StatefulBeanToCsvBuilder<T>(writer).build();
            beanToCsv.write(exportResults);
            // 写出到临时文件完成后,读取此临时文件
            return new FileInputStream(tempFile);
        } catch (Exception e) {
            log.error("csv文件上传失败");
            log.error(e.getMessage(), e);
        } finally {
            try {
                assert csvWriter != null;
                csvWriter.close();
                writer.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }
}
©️2020 CSDN 皮肤主题: 黑客帝国 设计师:上身试试 返回首页