
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Close Input Stream and Release System Resources in Java
This Java article discusses the InputStream.close() function to close the input stream and free up system resources. The method java.io.InputStream.close() is used to close this input stream and release any system resources associated with the stream. This method requires no parameters and returns no value. Also, the IOException is thrown when an I/O error occurs.
Problem Statement
Given an input stream, write a Java program to close this input stream and release any system resources associated with it. Ensure that the program handles any exceptions that may occur if the stream is already closed or an I/O error is encountered.Input
An input stream that reads a file located at C://JavaProgram//data.txt.Output
The number of bytes are: 4
Error!!! The input stream is closed
Steps to close the input stream and release system resources
The following are the steps to close the input stream and release system resources
- Import the necessary classes from the java.io package (FileInputStream and InputStream).
- Create an InputStream object and use the FileInputStream to read a file.
- Retrieve the available bytes using the available() method to check the current status of the stream.
- Close the input stream using the close() method to release resources.
- Attempt to access the input stream again after closing it, and handle any exceptions that occur, such as an IOException.
Java program to close an InputStream and release resources
The following is an example of closing an InputStream and releasing resources
import java.io.FileInputStream; import java.io.InputStream; public class Demo { public static void main(String[] args) throws Exception { InputStream i = null; int num = 0; try { i = new FileInputStream("C://JavaProgram//data.txt"); num = i.available(); System.out.println("The number of bytes are: " + num); i.close(); num = i.available(); System.out.println("The number of bytes are: " + num); } catch(Exception e) { System.out.print("Error!!! The input stream is closed"); } } }
Output
The number of bytes are: 4 Error!!! The input stream is closed
Code Explanation
Using the FileInputStream class, an input stream is created, the number of bytes that can be read is checked with available() and the output is shown. When a stream is closed using close(), and there is an attempt to read the stream, an exception occurs since the stream is already closed. The exception is handled and a message "Error!!! The input stream is closed" is shown as a part of the error handling.Advertisements