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

com.xinput.bleach.util.FileHelper Maven / Gradle / Ivy

The newest version!
package com.xinput.bleach.util;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.univocity.parsers.common.processor.BeanListProcessor;
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;

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

/**
 * @author xinput
 * @date 2019-09-27 11:21
 */
public class FileHelper {

    public static  T readFileBean(String fileName, Class clazz) throws IOException {
        String demoTaskString = Files.asCharSource(new File(fileName), Charsets.UTF_8).read();
        return JsonUtils.toBean(demoTaskString, clazz);
    }

    public static  List readFileList(String fileName, Class clazz) throws IOException {
        String demoTaskString = Files.asCharSource(new File(fileName), Charsets.UTF_8).read();
        return JsonUtils.toList(demoTaskString, clazz);
    }

    /**
     * 将csv文件内容转为实体对象
     *
     * @param csvText
     * @param clazz
     * @param 
     * @return
     */
    public static  List readCsv(String csvText, Class clazz) {
        return readCsv(csvText, 0, clazz);
    }

    /**
     * @param csvText
     * @param skipRowNum
     * @param clazz
     * @param 
     * @return
     */
    public static  List readCsv(String csvText, int skipRowNum, Class clazz) {
        BeanListProcessor rowProcessor = new BeanListProcessor<>(clazz);
        CsvParserSettings parserSettings = new CsvParserSettings();
        parserSettings.setProcessor(rowProcessor);
        parserSettings.getFormat().setLineSeparator("\n");
        parserSettings.getFormat().setDelimiter('\t');
        parserSettings.setNumberOfRowsToSkip(skipRowNum);

        CsvParser parser = new CsvParser(parserSettings);
        parser.parse(new StringReader(csvText));

        return rowProcessor.getBeans();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy