×

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with a try with the resource it must be closed. In Java 9 we have the Try-with Resources functionality which ensures the user that the resource object will be closed whenever the requirement finishes. It increases the efficiency of the program. It reduces the overhead of closing the file connection, network connection explicitly.

Java 9 Try With Single Resources Example:

import java.io.*;


public class Main {
public static void main(String[] args)
{
try (FileOutputStream fosout= new FileOutputStream("file.txt")) {


String text = " Hello, Welcome to Try with resource feature of Java 9 ";
           byte array[] = text.getBytes();
           fosout.write( array );
}
catch (Exception e) {
              System.out.println(e);
}


System.out.println(" Message has been written in the file.txt and resources are closed successfully ");
}


}

Output:

Java 9 Try With Resources

Explanation:

In java 9, we have the facility to use try with resource functionality. We have declared one class main inside which the file outstream object created inside the try. The byte array is obtained from text using the getBytes() method. Then this content is written into the file outstream object and then try with resource functionality in java 9 closes all the connections without forcing the user to manually do it. And then the message is printed " Message has been written in the file.txt and resources are closed successfully " with file written with the message " Hello, Welcome to Try with resource feature of Java 9 ".

Java 9 Try With Multiple Resources Example:

import java.io.*;


public class Main {


public static void main(String[] args) {

      try ( FileOutputStream fosout =  new FileOutputStream ( "output.txt" );
      BufferedReader br = new BufferedReader( new FileReader( "file.txt" )))
      {
          String text;
          while (( text = br.readLine()) != null ) {
              byte array[] = text.getBytes();
              fosout.write(array);
       }


       System.out.println("File content copied from one file another file.");
       }


       catch (Exception e) {
             System.out.println(e);
       }


       System.out.println(" Message has been written in the output.txt and resources are closed successfully ");
}
}

Output:

Java 9 Try With Resources

Explanation:

In java 9, we have the facility to use multiple try with resource functionality. We have declared one class main inside which the file outstream object created inside the try. Also, the BufferedReader object is created having the file.txt passed inside it. Then using this object we are reading the content from file.txt and writing it to the another file and then try with resource functionality in java 9 closes all the connection without forcing the user to manually do it. And then the message is printed "File content copied from one file another file." Also prints, " Message has been written in the output.txt and resources are closed successfully " with file written with the message " Hello, Welcome to Try with resource feature of Java 9. File content copied from file.txt to output.txt ".

Java 9 Try With Resource Improvement:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;


public class Main {
   public static void main(String[] args) throws IOException {
     
      System.out.println( check1(" Java Earlier version require extra br object "));
      System.out.println( check2(" Java 9 dont require extra br object for reading "));


   } 
    static String check1(String message) throws IOException {
      Reader input = new StringReader( message );
      BufferedReader br = new BufferedReader( input );


      try ( BufferedReader br1 = br ) {
         return br1.readLine();
      }


   }
   
    static String check2(String message) throws IOException {
      Reader input = new StringReader( message );
      BufferedReader br = new BufferedReader( input );


      try (br) {
         return br.readLine();
      }
   }


   }

Output:

Java 9 Try With Resources

Explanation:

In java 9, we have the facility to use try with resource functionality. It improves the efficiency of the code. In this, we have declared one class main inside which we have created two method check1() and check2(). The check1() method shows the functionality using the java earlier versions in which the BufferedReader object is created the first time to store the Reader input and again we have to create the second BufferedReader object br1 which stores br content and then return it. Rather in the check2() method which uses the java 9 functionality single BufferedReader br is created which stores the input message and also returns content with the same br object. In this way, Java 9 provides user convenience and saves time using try with resource functionality.


Related Topics

Concurrent Linked Deque in Java with Examples

Introduction Java's concurrent-linked deque, which holds its items as linked nodes, is unconstrained and thread-safe. Concurrent Linked Deque allows for element removal and addition on both sides because it implements the...

4 minutes read.

Dining Philosophers problem in Java

The Problem of the Dining Philosophers illustrates a concurrency issue involving the distribution of scarce resources among conflicting processes. Problem Statement Imagine a dining table with a circle in the middle and five...

3 minutes read.

How to check valid date in Java?

Every time we get data for any application, we must first ensure that it is accurate before continuing with any further processing. We might have to confirm the following while dealing...

4 minutes read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

Java program to count the occurrences of each character

The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2,...

6 minutes read.

Determine the Upper Bound of a Two-Dimensional Array in Java

Multi-Dimensional Array Multi-faceted exhibits in Java are regular and can be named various clusters. Information in a two-layered bunch in Java is put away in 2D even structure. A two-layered collection...

3 minutes read.

How to Convert String to Integer in Java

How to convert String to int in Java You need to convert String into int if you want to perform a mathematical operation on string which contains digits. To do so,...

3 minutes read.

Undo and Redo Operations in Java

Undo and redo operation are the most widely used operation while dealing with file. In this section, we will discuss how to implement undo and redo operation in Java. Undo Redo...

2 minutes read.

Design of JDBC

Java applications may interface using database systems from many vendors using the Java Database Connectivity (JDBC) Application Software Interface (API) from Sun Microsystem. To connect spreadsheets, JDBC and database drivers...

3 minutes read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

Graph Problems in Java

A graph is a special type of data structure used in programming that is made up of edges connecting each set of finitely many nodes, or vertices, to each other....

14 minutes read.

Java URL Class with Example

Java URL Uniform Resource Locator To find any resource on the internet, you need to have an address of it. The URL and IP addresses are the pointers used for this purpose....

12 minutes read.

How to Convert char to int in Java

How to Convert char to int in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

3 minutes read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

Java ArraylistRemove() Time Complexity

In this tutorial, we will learn about how we can remove time complexity in Java ArrayList. But unless we will not learn what is ArrayList, we don’t understand this process....

7 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

Java Integer divideUnsigned() method

The divideUnsigned() method of Integer class returns the unsigned quotient by dividing the first argument by the second argument. Syntax public static int divideUnsigned (int dividend , int divisor) Parameters The parameter ‘dividend’ represents...

1 minute read.