我正在尝试读取CSV文件,然后根据该CSV文件创建新对象。我可以使用SuperCSV库成功完成此操作,但如果发生错误(例如特定单元格为null),则会抛出错误(如预期的那样)。我试图收集ArrayList中的所有错误,但是现在在第一个异常时,一切都会停止。即使处理器出错,我如何让SuperCSV CsvBeanReader继续下一行?我在try / catch块中有循环条件。代码如下:
ArrayList<Duplicate> duplicates = new ArrayList<Duplicate>();
ArrayList<BadProperty> invalidProperties = new ArrayList<BadProperty>();
File convFile = new File(file.getOriginalFilename());
convFile.createNewFile();
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(file.getBytes());
fos.close();
ICsvBeanReader beanReader = null;
try {
beanReader = new CsvBeanReader(new FileReader(convFile), CsvPreference.STANDARD_PREFERENCE);
final String[] header = beanReader.getHeader(true);
final CellProcessor[] processors = getProcessors();
Property property;
while ((property = beanReader.read(Property.class, header, processors)) != null) {
// logic in here
}
}
catch(SuperCsvException e) {
invalidProperties.add(new BadProperty(e.getCsvContext()));
System.out.println(e);
}
finally {
if( beanReader != null ) {
beanReader.close();
}
}
答案 0 :(得分:1)
最重要的是在循环中移动try catch,这样在发生异常时循环不会停止。我就是这样做的
private void readProperties()
{
try
{
beanReader = new CsvBeanReader(new FileReader(convFile), CsvPreference.STANDARD_PREFERENCE);
while (readNextProperty())
{
}
}
catch (Exception e)
{
}
finally
{
if(beanReader != null)
{
beanReader.close();
}
}
}
/** Returns true when there are more properties to read. */
private boolean readNextProperty()
{
try
{
Property property = beanReader.read(Property.class, header, processors);
if (property == null)
{
return false;
}
// logic in here
}
catch (SuperCsvException e)
{
invalidProperties.add(new BadProperty(e.getCsvContext()));
System.out.println(e);
}
return true;
}