- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is try-with-resource in java?
Whenever we instantiate and use certain objects/resources we should close them explicitly else there is a chance of Resource leak.
From JSE7 onwards the try-with-resources statement is introduced. In this we declare one or more resources in the try block and these will be closed automatically after the use. (at the end of the try block)
The resources we declare in the try block should extend the java.lang.AutoCloseable class.
Example
Following program demonstrates the try-with-resources in Java.
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class FileCopying { public static void main(String[] args) { try(FileInputStream inS = new FileInputStream(new File("E:\Test\sample.txt")); FileOutputStream outS = new FileOutputStream(new File("E:\Test\duplicate.txt"))){ byte[] buffer = new byte[1024]; int length; while ((length = inS.read(buffer)) > 0) { outS.write(buffer, 0, length); } System.out.println("File copied successfully!!"); } catch(IOException ioe) { ioe.printStackTrace(); } } }
Output
File copied successfully!!
- Related Articles
- What is the try block in Java?
- What are the improvements for try-with-resources in Java 9?\n
- What are try, catch, finally blocks in Java?
- Effectively final variables in try-with-resources in Java 9?
- What is Human Resource Management?
- Automatic resource management in Java\n
- What is RSVP (Resource Reservation Protocol)?
- Is it possible to have multiple try blocks with only one catch block in java?
- Try-with-resources in Kotlin
- Can we define a try block with multiple catch blocks in Java?
- Try, catch, throw and throws in Java
- What happens if we try to extend a final class in java?
- How to declare multiple resources in a try-with-resources statement in Java 9?
- Nested try blocks in Exception Handling in Java
- Can we declare a try catch block within another try catch block in Java?

Advertisements