All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gitee.cliveyuan.tools.CsvTools Maven / Gradle / Ivy

There is a newer version: 4.0.6
Show newest version
package com.gitee.cliveyuan.tools;

import com.gitee.cliveyuan.tools.data.TableUtils;
import com.gitee.cliveyuan.tools.data.csv.CsvReader;
import com.gitee.cliveyuan.tools.data.csv.CsvWriter;
import com.gitee.cliveyuan.tools.exception.CsvException;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.PropertyDescriptor;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import static com.gitee.cliveyuan.tools.data.TableUtils.SDF;

/**
 * @author clive
 * Created on 2018/08/01
 * @since 1.0
 */
public class CsvTools {

    private static final Logger logger = LoggerFactory.getLogger(CsvTools.class);

    private final static String CSV = "csv";
    private static final String EXTENSION = "." + CSV;


    /**
     * 读取CSV文件
     *
     * @param csvReader csvReader
     * @param        对应的实体
     * @return 数据列表
     */
    public static  List read(CsvReader csvReader) {
        Assert.notNull(csvReader, "csvReader is required");
        Assert.notNull(csvReader.getFilePath(), "filePath is required");
        Assert.notNull(csvReader.getClazz(), "clazz is required");
        List data = CsvTools.readRawCsv(csvReader.getFilePath(), csvReader.getEncoding());
        return TableUtils.dataToObject(csvReader.getSkipRowNo(), data, csvReader.getClazz());
    }

    /**
     * 写入CSV文件
     *
     * @param csvWriter csvWriter
     * @param        对应的实体
     * @return CSV文件
     */
    public static  File write(CsvWriter csvWriter) {
        Assert.notEmpty(csvWriter.getHeaders(), "headers can't be empty");
        Assert.notEmpty(csvWriter.getData(), "data can't be empty");
        Assert.notNull(csvWriter.getFilePath(), "file path can't be empty");
        return doWrite(csvWriter);
    }

    /**
     * 读入原生csv文件,解析后返回
     *
     * @param absoluteFilePath 文件绝对路径
     */
    public static List readRawCsv(String absoluteFilePath, String encoding) throws CsvException {
        Assert.notBlank(absoluteFilePath, "csv file path is empty");
        File file = new File(absoluteFilePath);
        Assert.isTrue(file.exists(), "csv file not exists");
        List list = Lists.newArrayList();
        try {
            String extension = FileTools.getExtension(absoluteFilePath);
            if (!CSV.equalsIgnoreCase(extension)) {
                throw CsvException.notSupport(extension);
            }
            List lines = FileTools.readFileToStringList(file, encoding);
            lines.forEach(line -> list.add(line.split(",")));
        } catch (CsvException e) {
            throw e;
        } catch (Exception e) {
            logger.error("readCsv ", e);
            throw CsvException.failToParseCsv();
        }
        return list;
    }

    //region private methods

    private static  File doWrite(CsvWriter csvWriter) {
        String filePath = csvWriter.getFilePath();
        String[] headers = csvWriter.getHeaders();
        Collection data = csvWriter.getData();
        File file = new File(filePath);
        if (!file.exists()) {
            boolean result = file.mkdirs();
            if (!result) {
                throw CsvException.failToMkdirs();
            }
        }
        String fileName = System.currentTimeMillis() + EXTENSION;
        if (!filePath.endsWith(File.separator)) {
            filePath = filePath + File.separator;
        }
        file = new File(filePath + fileName);
        try {
            StringBuilder content = new StringBuilder();
            // header
            for (String header : headers) {
                content.append(header).append(",");
            }
            content.deleteCharAt(content.length() - 1);
            content.append("\n");

            // data
            for (T t : data) {
                //反射
                Class clazz = t.getClass();
                Field[] fields = clazz.getDeclaredFields();
                for (Field field : fields) {
                    PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
                    Method getMethod = pd.getReadMethod();
                    if (getMethod != null) {
                        Object invoke = getMethod.invoke(t);
                        String value = StringTools.EMPTY;
                        if (invoke != null) {
                            if (invoke instanceof Date) {
                                value = SDF.format((Date) invoke);
                            } else {
                                value = invoke.toString();
                            }
                        }
                        content.append(value).append(",");
                    }
                }
                content.deleteCharAt(content.length() - 1);
                content.append("\n");
            }
            FileTools.writeStringToFile(file, content.toString(), csvWriter.getEncoding());
            return file;
        } catch (Exception e) {
            logger.error("excel generate exception", e);
            throw CsvException.failToGenerateCsv();
        }
    }
    //endregion
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy