Need universal method to read csv files

风流意气都作罢 提交于 2020-06-13 06:26:09

问题


I am working on spring web based application in which I facilitate the user to upload the csv files and all the content of csv file will be stored in my MySQL database. I ma using OpenCsv for reading the CSV files, I wrote a method, which I want to be universal, because right now It only written for my Model Employee, I want to be use it as Utility class.

Here it is

public static List<Employee> parseCSVWithHeader() throws IOException {
    CSVReader reader = new CSVReader(new FileReader("emps1.csv"), ',');

    HeaderColumnNameMappingStrategy<Employee> beanStrategy = new HeaderColumnNameMappingStrategy<Employee>();
    beanStrategy.setType(Employee.class);

    CsvToBean<Employee> csvToBean = new CsvToBean<Employee>();
    List<Employee> emps = csvToBean.parse(beanStrategy, reader);

    System.out.println(emps);
    reader.close();

    return emps;
} 

回答1:


Assuming I understand what you mean by universal, you can make the method generic on some type T. You will need to pass the Class<T> as a parameter (e.g. Employee.class). You should also pass in the file to be read. And, assuming CSVReader is closable, I would prefer a try-with-resources. Like,

public static <T> List<T> parseCSVWithHeader(Class<T> cls, String fileName) 
                throws IOException {
    try (CSVReader reader = new CSVReader(new FileReader(fileName), ',')) {
        HeaderColumnNameMappingStrategy<T> beanStrategy = new HeaderColumnNameMappingStrategy<>();
        beanStrategy.setType(cls);

        CsvToBean<T> csvToBean = new CsvToBean<>();
        List<T> emps = csvToBean.parse(beanStrategy, reader);
        System.out.println(emps);
        return emps;
    }
}


来源:https://stackoverflow.com/questions/53587978/need-universal-method-to-read-csv-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!