问题
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