top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

What is try-with-resources in java?

+1 vote
42 views
What is try-with-resources in java?
posted Jun 7, 2016 by Karthick.c

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes
 
Best answer

try-with-resources is an interesting concept in java. The purpose of this is to auto dispose/close the resource as soon as it serves its purpose.

For instance in Java 6 and below, a buffer reader is initialized and closed manually in try's finally block.

BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
}

Now, with try-with-resources, (started supported BufferedReader from Java 7) it is automatically closed as soon the try statement block executes completely. It closes automatically, irrespective of success or error of try block.

try (BufferedReader br = new BufferedReader(new FileReader(path))) {
     return br.readLine();
}

Note: java.lang.AutoCloseable must be implemented for any class to support try-with-resources.

Hope this helps.

answer Jun 24, 2016 by Vinod Kumar K V
Similar Questions
+3 votes

Implement a code that counts the occurrences of each word in an input file and write the word along with corresponding count in an output file sorted by the words alphabetically.

Sample Input

Gaurav is  a Good Boy
Sita is a Good Girl
Tommy is  a Good Dog
Ram is a Good person

Sample Output

D:\>Java FileWordCount inputFile.txt outputFile.txt
    Boy : 1
    Dog : 1
    Gaurav : 1
    Girl : 1
    Good : 4
    Ram : 1
    Sita : 1
    Tommy : 1
    a : 4
    is : 4
    person : 1
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...