java 9 - topjavatutorial.com

Java 9 : Try-with-Resources enhancement

try-with-resources Statement

Java 7 added a new feature try-with-resources that automates resource management.

It looks like this :


try (Resource r1 = new Resource("resource1"); Resource r2 = new Resource("resource1")) {

  // use the resource

}

When the try block ends, the resource is automatically released.

Example :

private void readFile() throws IOException {
  int i;

  try (FileInputStream fin = new FileInputStream("in.txt");) {
    do {
      i = fin.read();
      if (i != -1) {
        System.out.println((char) i);
      }
    } while (i != -1);
  }
}

 

Java 9 enhancement for try-with-resources

Java 9 introduced an enhancement where if the resource is referenced by a final or effectively final variable, try-with-resources statement doesn’t need a new variable being declared.


Resource r1 = new Resource("resource1");
Resource r1 = new Resource("resource1");
try (r1;r2) {
    // use the resource
}

Example :

private void readFile() throws IOException{
  int i;
  FileInputStream fin = new FileInputStream("in.txt");
  
    try(fin){
        do{
            i = fin.read();
            if(i!=-1){
                System.out.println((char)i);
            }
        }while(i!=-1);
    }
}

© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags