在 customReaderItem 中管理 I/O 和 POI 异常
Manage I/O and POI exception in a customReaderItem
我正在使用实现 ItemReader
的 customReader
。我的 reader 从 xls 中获取信息并逐行处理。我的构造函数采用 Iterator
值,每次 read()
迭代都会读取该值。我正在尝试找到一种合适的方法来管理异常。我浏览了 SkipListener
和 ReaderListener
onReadError
。但是我不能使用任何一个,因为在尝试 read()
方法之前,我的异常将在构造函数中抛出。
有什么方法可以让我正确管理 action1/2/3 分别处理异常情况?
@Component
public class CustomReaderFile implements ItemReader<Row> {
private final Iterator<Row> data;
private static final String FILE_NAME = "";
public CustomReaderFile() throws Exception {
this.data = iteratorFromXls();
}
@Override
public Row read() throws Exception {
if (this.data.hasNext()) {
return this.data.next();
} else {
return null;
}
}
public static Iterator<Row> iteratorFromXls() throws Exception {
Iterator<Row> iterator = null;
try {
FileInputStream excelFile = new FileInputStream(new File(FILE_NAME));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet dataTypeSheet = workbook.getSheetAt(0);
iterator = dataTypeSheet.iterator();
} catch (FileNotFoundException e) {
//action1
} catch (IOException e) {
//action2
} catch (NotOfficeXmlFileException e){
//action3
}
return iterator;
}
这实际上是reader的初始化代码。读取部分无非就是在迭代器上调用.next
。
所以我会让 reader 实现 ItemStreamReader
并将初始化代码放在 open
方法中,您可以在其中抛出异常以向 Spring 发出信号reader 初始化失败的批次。
我正在使用实现 ItemReader
的 customReader
。我的 reader 从 xls 中获取信息并逐行处理。我的构造函数采用 Iterator
值,每次 read()
迭代都会读取该值。我正在尝试找到一种合适的方法来管理异常。我浏览了 SkipListener
和 ReaderListener
onReadError
。但是我不能使用任何一个,因为在尝试 read()
方法之前,我的异常将在构造函数中抛出。
有什么方法可以让我正确管理 action1/2/3 分别处理异常情况?
@Component
public class CustomReaderFile implements ItemReader<Row> {
private final Iterator<Row> data;
private static final String FILE_NAME = "";
public CustomReaderFile() throws Exception {
this.data = iteratorFromXls();
}
@Override
public Row read() throws Exception {
if (this.data.hasNext()) {
return this.data.next();
} else {
return null;
}
}
public static Iterator<Row> iteratorFromXls() throws Exception {
Iterator<Row> iterator = null;
try {
FileInputStream excelFile = new FileInputStream(new File(FILE_NAME));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet dataTypeSheet = workbook.getSheetAt(0);
iterator = dataTypeSheet.iterator();
} catch (FileNotFoundException e) {
//action1
} catch (IOException e) {
//action2
} catch (NotOfficeXmlFileException e){
//action3
}
return iterator;
}
这实际上是reader的初始化代码。读取部分无非就是在迭代器上调用.next
。
所以我会让 reader 实现 ItemStreamReader
并将初始化代码放在 open
方法中,您可以在其中抛出异常以向 Spring 发出信号reader 初始化失败的批次。