×

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

Class definition in Java

The class definition in Java Java is an object-oriented programming language. We essentially know that programming languages based on object-oriented paradigms have classes and objects in their concepts as main, which...

6 minutes read.

Java Integer compare() method

The compare() method of Integer class compares the two specified int values. Syntax public static int compare(int x, int y) Parameters The parameters ‘x’ and ‘y’ represent the first and second int values to...

2 minutes read.

Java Math floorMod() Method

The floorMod() method of Math class returns the floor modulus of the specified arguments. It firstly divides the dividend and divisor and then returns an integer that is equal to...

1 minute read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

Program to Implement FLAMES Game in Java

Friends, Lovers, Affectionate, Marriage, Enemies, and Sibling are all represented by the acronym FLAMES, which also serves as the name of a well-known game. Although, it can be entertaining to...

4 minutes read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

Memory Leak in Java

Java offers memory management right out of the box. When we use the new keyword to create an object, the JVM initialises for that object immediately. The trash collector automatically...

3 minutes read.

Java Map Example

In Java, the Map is an interface that is used mainly to denote key and value pairs. The central concept and theme of this mapping in the java collection framework...

4 minutes read.

Java file Reader

File Reader: It is used to read the data from files. This class inherits the properties from Input Stream Reader Class. File Reader is for reading characters from the file. Input Stream: Java.io...

4 minutes read.

Enum Java Interview Questions

1. What exactly is Java? Java is a portable, high-level, object-oriented, robust, secure, platform-independent, multi-threaded, high-performance programming language. Developed in June 1991 by James Gosling, also known as Platform. 2. Enum is...

3 minutes read.

Java Open File

Java Desktop class give an open() strategy to open a filr. It has a place with a java.awt package. Work area execution is stage subordinate, so it is important to...

5 minutes read.

Interleaving string in Java

If the string Str3 contains all of the characters from Str1 and Str2, it is considered interleaving Str1 and Str2. Keep in mind that the order of all characters in...

5 minutes read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

Java Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.

Minimum XOR value pair in Java

In this section, you will discuss about minimum XOR value pair in Java. The objective is to enforce a value that indicates the least XOR values of the two numbers from...

4 minutes read.

Longest Arithmetic Progression Sequence in Java

The task is to find the length of the largest sequence in an array to form an arithmetic progression. The array arr[] is given. Longest Arithmetic Progression Sequence in Java Algorithm set...

5 minutes read.

Reverse a String in Java

Reversing a string means that if we have a string called “what is your name”, the reversed format is “eman ruoy si tahw”. Reversing a string involves totally flipping the...

3 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

XNOR operator in Java

The opposite of the binary equivalent of XOR is given by XNOR. Truth table: XYXNOR001010100111 If the bits are the same, it returns 1, else it returns 0. Examples:  Input: 10 20 Output : 1 A Binary...

3 minutes read.

Java Integer reverseByte() method

The reverseByte() method of Java Integer class returns the value obtained by reversing the order of the bytes in the 2’s complement binary representation. Syntax public static int reverseByte (int i) Parameters The parameter...

1 minute read.