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

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

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

import com.gitee.cliveyuan.tools.Assert;
import com.gitee.cliveyuan.tools.FileTools;
import com.gitee.cliveyuan.tools.exception.CsvException;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.List;

/**
 * @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";

    /**
     * 读入csv文件,解析后返回
     *
     * @param absoluteFilePath 文件绝对路径
     */
    public static List readCsv(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;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy