在此代码中,目标是解析CSV文件并将其数据映射到bean对象。

ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy();
strat.setType(Country.class);
String[] columns = new String[] {"countryName", "capital"};
strat.setColumnMapping(columns);

CsvToBean csv = new CsvToBean();

String csvFilename = "C:/Users/user/Desktop/sample.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));


文件中的列具有标题,有时还包含原始数据下方的其他信息(例如字符串或整数单元格中的数字或单词)。

我问了如何在先前的问题中忽略这些附加信息,并获得了以下代码作为答案:

List<Country> list = new ArrayList<Country>();
String [] row = csvReader.readNext(); //skip header
    if(row == null) throw new RuntimeException("File is empty");
    row = csvReader.readNext();
    String [] nextRow = csvReader.readNext();
    while(row != null) {
       if(nextRow == null) break; //check what 'row' is last
       if("Total:".equalsIgnoreCase(row[1])) break; //check column for special strings

       list.add(csv.processLine(strat, row)); <----

       row = nextRow;
       nextRow = csvReader.readNext();


当我尝试实现此代码时,在箭头标记的行上出现了两个错误。


  线程“主”中的异常java.lang.Error:未解决的编译
  问题:
  
  类型List中的方法add(Country)不是
  适用于参数(对象)
  
  CsvToBean类型的方法processLine(MappingStrategy,String [])不可见


有人知道如何解决这个问题吗?我是Java的新手。

非常感谢你。

最佳答案

类型的方法processLine(MappingStrategy,String [])
  CsvToBean不可见


表示此方法必须是可访问的(可能的原因;它是私有的,受保护的或友好的),因此请使用public


  类型List中的add(Country)方法不适用于
  参数(对象)


并且必须返回国家(地区)类型,方法签名必须类似;

public Country processLine(ColumnPositionMappingStrategy strat, String [] row)

10-07 19:31
查看更多