我有一段代码,我正在尝试使用资源来处理流。我也有一行调用一个可能抛出IOException的函数。
由于组织其他业务逻辑的方式,我不想让函数抛出IOException。到目前为止,这就是我所拥有的 -
try {
final List<Map<?, ?>> data = readObjectsFromCsv(options.getInputFile());
try (
ByteArrayOutputStream jsonEarningsData = writeAsJson(data);
InputStream jsonData = new ByteArrayInputStream(jsonEarningsData.toByteArray());
InputStream csvEarningsData = new FileInputStream(options.getInputFile());)
{
final String key = join(UNDERSCORE, Arrays.asList(UUID.randomUUID(), formattedDate, options.getProgram()));
final String jsonKey = join(EMPTY, Arrays.asList(key, EXTENSION_JSON));
final String csvKey = join(EMPTY, Arrays.asList(key, EXTENSION_CSV));
uploadFile(csvEarningsData, earningsDataBucketPrefix, csvKey);
uploadFile(jsonData, earningsDataBucketPrefix, jsonKey);
}
} catch (IOException e) {
log.error("Failure from File IO: ", e);
}
然而,我讨厌这段代码是如何组织的,而且看起来总体上很难看。我希望得到关于如何更好地模拟这段代码的想法。
编辑:我从try-catch中分离出数据初始化,并编写了一个内部方法来处理try with resources部分。这就是我最终提出的比初始方法更清晰的东西 -
public void execute() {
try {
final File csvEarningsFile = options.getInputFile();
final List<Map<?, ?>> data = readObjectsFromCsv(csvEarningsFile);
uploadFileInitializer(data, csvEarningsFile);
} catch (IOException e) {
log.error("Failure from File IO: ", e);
}
}
private void uploadFileInitializer(List<Map<?,?>> data, File csvEarningsFile) throws IOException{
final String key = join(UNDERSCORE, Arrays.asList(UUID.randomUUID(), formattedDate, options.getProgram()));
final String jsonKey = join(EMPTY, Arrays.asList(key, EXTENSION_JSON));
final String csvKey = join(EMPTY, Arrays.asList(key, EXTENSION_CSV));
try (
ByteArrayOutputStream jsonEarningsData = writeAsJson(data);
InputStream jsonData = new ByteArrayInputStream(jsonEarningsData.toByteArray());
InputStream csvEarningsData = new FileInputStream(csvEarningsFile);
) {
uploadFile(csvEarningsData, earningsDataBucketPrefix, csvKey);
uploadFile(jsonData, earningsDataBucketPrefix, jsonKey);
}
}