StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Wednesday, May 28, 2014

Java 7 try-with-resources

 May 28, 2014     Java     No comments   

Java 7 has introduced try-with-resources statement which ensures that resources (files or socket handles) declared in the statement are closed at the end of the statement. All objects implementing java.lang.AutoCloseable (AutoCloseable) can be used as a resource. Usage of try-with-resources ensures release of resources which otherwise would cause resource exhaustion and exceptions.

Prior to Java 7 resources are closed in the finally block. The finally block gets executed regardless of whether the try block completes successfully or not.

Let us consider a simple example to copy an input file to an output file prior to Java 7. In the implementation below FileInputStream and FileOutputStream are closed in the finally block.

public static void java6FileCopy() {
  FileInputStream fis = null;
  FileOutputStream fos = null;
  try {
    fis = new FileInputStream(new File("resources/input.txt"));
    fos = new FileOutputStream(new File("resources/output.txt"));
    int data = fis.read();
        while (data != -1)
        {          
            fos.write(data);
            data = fis.read();
        }
  } catch ( IOException e ) {
    e.printStackTrace();
  }
  finally {
    try {
      if ( fis != null ) fis.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    try {
      if ( fos != null ) fos.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
In Java 7 we can use the try-with-resources statement to declare the resources. This ensures that FileInputStream and FileOutputStream are automatically closed at the end of the try block.
public static void java7FileCopy() {
    try ( FileInputStream fis = new FileInputStream(new File("resources/input.txt"));
        FileOutputStream fos = new FileOutputStream(new File("resources/output.txt")); ) {
    int data = fis.read();
    while (data != -1)
    {          
        fos.write(data);
        data = fis.read();
    }
  } catch ( IOException e ) {
    e.printStackTrace();
  } 
}
Using try-with-resources makes the code more elegant and there is no need to close the resources explicitly.
Email ThisBlogThis!Share to XShare to Facebook
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Python FastAPI file upload and download
    In this article, we will look at an example of how to implement a file upload and download API in a Python FastAPI microservice. Example bel...
  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Accessing the Kubernetes API
    In this article, we will explore the steps required to access the Kubernetes API and overcome common challenges. All operations and communic...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Scheduling jobs in Python
    When developing applications and microservices we run into scenarios where there is a need to run scheduled tasks. Examples include performi...
  • Using Tekton to deploy KNative services
    Tekton is a popular open-source framework for building continuous delivery pipelines. Tekton provides a declarative way to define pipelines ...

Copyright © StackStalk