Categories: Uncategorised

Try with Resources

Developers who have used sonar for code analysis would have seen this check Try-with-resources should be used. Try-with-resources statement was introduced in Java 7 which guarantees that the resources will be closed. Lets see this in detail using the below example.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

 private static String fileName = "D:\\proverbs.txt";

 public static void main(String args[]) {

  readFile(fileName);
 }

 private static void readFile(String fileName) {
  File file = new File(fileName);

  try (FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr)) {

   String line;

   while ((line = br.readLine()) != null) {

    System.out.println(line);
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }

 }
}

In the above code we could see logic to read a file and print its contents. For reading the file we have used FileReader and BufferedReader which are classes that implement Closeable interface which has method close used to close the stream.

package java.io;

import java.io.IOException;

/**
 * A {@code Closeable} is a source or destination of data that can be closed.
 * The close method is invoked to release resources that the object is
 * holding (such as open files).
 *
 * @since 1.5
 */public interface Closeable extends AutoCloseable {

    /**
     * Closes this stream and releases any system resources associated
     * with it. If the stream is already closed then invoking this
     * method has no effect.
     *
     * <p> As noted in {@link AutoCloseable#close()}, cases where the
     * close may fail require careful attention. It is strongly advised
     * to relinquish the underlying resources and to internally
     * <em>mark</em> the {@code Closeable} as closed, prior to throwing
     * the {@code IOException}.
     *
     * @throws IOException if an I/O error occurs
     */    public void close() throws IOException;
}

When we create the classes which implement Closeable interface using try-with-resources the close methods of these objects are automatically called either the flow terminates normally or with an exception.

mahendravarman.m@gmail.com

Recent Posts

Spring Webflux Functional Endpoint – File Upload

In this blog using the Spring WebFlux module, we are going to leverage the functional…

11 months ago

Serverless Functions with Spring Cloud Function, AWS Lambda

Spring Cloud Function is a project within the Spring ecosystem that allows developers to build…

11 months ago

Spring Boot + RabbitMQ – Decoupling Microservices Communication

RabbitMQ is an open-source message broker software that implements the Advanced Message Queuing Protocol (AMQP).…

12 months ago

Spring Integration – Sending files over SFTP

Spring Integration is a powerful extension of the Spring Framework designed to support the implementation…

12 months ago

Spring Cloud Config Client

The Spring Cloud Config Client is a component of the Spring Cloud framework that enables…

1 year ago

Handling CSV in Python

In Python, handling CSV (Comma Separated Values) files is easy using the built-in csv module.…

1 year ago