Home Java Jdk7 The try-with-resource Statement
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

The try-with-resource Statement

Advertisement
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

 

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 2, 2011

Related Tutorials

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

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com