Total Pageviews

2016/09/09

[Java] try-with-resources statement

JDK 7 introduces a new version of try statement known as try-with-resources statement. This feature add another way to exception handling with resources management,it is also referred to as automatic resource management.

If this class implements AutoClossable interface, then you can make good use of  try-with-resources statement. Do not need to close manually.
e

As-is (does not apply try-with-resources statement)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
  FileOutputStream outputStream = null;
  File tmpFile = null;
  try {
      tmpFile = File.createTempFile("issue", ".xls");
      outputStream = new FileOutputStream(tmpFile);
      workbook.write(outputStream);
  } catch (FileNotFoundException e) {
      log.error(e.getMessage(), e);
  } finally {
      if (outputStream != null) {
          outputStream.close();
      }
      if (workbook != null) {
          workbook.close();
      }
  }


To-be (apply try-with-resources statement)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
  File tmpFile = File.createTempFile("issue", ".xls");
  try(FileOutputStream outputStream  = new FileOutputStream(tmpFile)){
      workbook.write(outputStream);
  } catch (FileNotFoundException e) {
      log.error(e.getMessage(), e);
  } finally{
      if (workbook != null) {
          workbook.close();
      }
  }


Reference
[1] http://www.studytonight.com/java/try-with-resource-statement.php

No comments: