Home Java Jdk7 The try-with-resource Statement



The try-with-resource Statement
Posted on: September 2, 2011 at 12:00 AM
In this section, you will learn about newly added try-with-resource statement in Java SE 7.

The try-with-resource Statement

In this section, you will learn about newly added try-with-resource statement in Java SE 7.

The try-with-resource statement contains declaration of one or more resources. As you know, prior to Java SE 7, resource object must be closed explicitly, when the resource use or work is finished. After the release of Java SE 7, the try-with-resource statement handles it implicitly means it automatically closed the resource when it has no longer use to the class. But for this, you need to declare resources using try-with-resource statement.

Given below the code for the above :

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

public class J7TryWithResource {
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path)))
{
System.out.println(br.readLine());
return br.readLine();
}
}

public static void main(String args[]) {
try {
readFirstLineFromFile("C://J7Try.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}

OUTPUT

C:\Program Files\Java\jdk1.7.0\bin>javac J7TryWithResource.java

C:\Program Files\Java\jdk1.7.0\bin>java J7TryWithResource
HI !! FOLKS...WELCOME 2 DEVMANUALS !!

Download Source Code

 

Related Tags for The try-with-resource Statement:


More Tutorials from this section

Ask Questions?    Discuss: The try-with-resource Statement  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.