參考致上述網址code如下:
ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy(); strat.setType(Country.class); String[] columns = new String[] {"countryName", "capital"}; // the fields to bind do in your JavaBean strat.setColumnMapping(columns); CsvToBean csv = new CsvToBean(); String csvFilename = "C:\\sample.csv"; CSVReader csvReader = new CSVReader(new FileReader(csvFilename)); List list = csv.parse(strat, csvReader); for (Object object : list) { Country country = (Country) object; System.out.println(country.getCapital()); }
package net.viralpatel.java; public class Country { private String countryName; private String capital; public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } public String getCapital() { return capital; } public void setCapital(String capital) { this.capital = capital; } }
以上Country class為inner class
但執行以上code時csv.parse() (LINE11)都會報錯:
java.lang.RuntimeException: Error parsing CSV!
仔細追了一下opencsv source發現,會在MappingStrategy.createBean()時發生
InstantiationException的錯誤,試驗一下發現原來inner class使用reflection的newInstance()都會出現這問題
因為opencsv中的parse會直接使用newInstance() create new instance,因此使用的TYPE不可為INNER CLASS
至於有沒有可以使用inner class的方式要再查查看
沒有留言:
張貼留言