尝试使用资源调用try块中的代码

时间:2017-12-21 17:16:24

标签: java

ZipFile zipFile = null;
InputStreamReader fileReader = null;
CSVParser csvReportParser = null;
List<CSVRecord> reportRecord = null;

try
{
  zipFile = new ZipFile(reportPath);
  Enumeration<? extends ZipEntry> entries = zipFile.entries();
  /** Assuming there is only one file in zip */
  ZipEntry entry = entries.nextElement();
  InputStream stream = zipFile.getInputStream(entry);
  fileReader = new InputStreamReader(stream, CHARSET_NAME);
  csvReportParser = new CSVParser(fileReader, csvFormat);
  reportRecord = csvReportParser.getRecords();
}
catch (FileNotFoundException e)
{
  LOG.error("File not found at path" + reportPath, e);
  throw new ClientConsoleException(e);
}
catch (IOException e)
{
  LOG.error("Error in reading file at path" + reportPath, e);
  throw new ClientConsoleException(e);
}
finally
{
  IOUtils.closeQuietly(csvReportParser);
  IOUtils.closeQuietly(fileReader);
  try
  {
    if (zipFile != null)
      zipFile.close();
  }
  catch (final IOException e)
  {
    LOG.error("Cannot close zip file" + reportPath, e);
  }
}

return reportRecord;

我想在上面的代码中使用try with resource。这里已经尝试了块,这里只有3个类可以在try with resource block中编写。 你可以帮我在资源上尝试使用正确的方法吗?

1 个答案:

答案 0 :(得分:0)

要将资源放入try-with-resource语句,请将其包装在括号中,如下所示:

public static List<CSVRecord> example() {
    CSVParser csvReportParser = null;
    List<CSVRecord> reportRecord = new ArrayList<>();
    String reportPath = "bla";

    try (ZipFile zipFile = new ZipFile(reportPath)) {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        ZipEntry entry = entries.nextElement();
        InputStream stream = zipFile.getInputStream(entry);

        try (InputStreamReader fileReader = new InputStreamReader(stream, CHARSET_NAME)) {
            // do stuff
        }
    } catch (IOException e) {
        // log
    } finally {
        IOUtils.closeQuietly(csvReportParser);
    }

    return reportRecord;
}

因为我不知道CSVParser是什么,所以我保持原样。如果它实现了Closable接口,那么CSVParser也可以包含在try-with-resources语句中:

try (ZipFile zipFile = new ZipFile(reportPath);
     CSVParser  csvReportParser = new CSVParser(fileReader, csvFormat)) {
    ...
}