

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Questions & Answers
- What is the try block in Java?
- What is Human Resource Management?
- What is RSVP (Resource Reservation Protocol)?
- What are the improvements for try-with-resources in Java 9?
- What are try, catch, finally blocks in Java?
- Automatic resource management in Java
- Try-with-resources in Kotlin
- Effectively final variables in try-with-resources in Java 9?
- Is it possible to have multiple try blocks with only one catch block in java?
- Try, catch, throw and throws in Java
- Is Canva Pro worth the try?
- Can we declare a try catch block within another try catch block in Java?
- Can we define a try block with multiple catch blocks in Java?
- How to use try-with-resources with JDBC?
- What happens if we try to extend a final class in java?
Advertisements