The close() method of BufferedInputStream class in Java closes the input stream and releases any system resources associated with it. Once the close() method is called, reading from any input file is banned and the system will throw an IOException. To tackle the issue, the user might use a try-catch block, to catch any such exception and throw a proper instruction.
Syntax:
public void close()
Parameters: This method does not accept any parameters.
Return value: This method does not return any value.
Overrides: The method is overridden by close in class FilterInputStream.
Exception: This method throws IOException if any input-output error occurs.
Below programs illustrates close() method in BufferedInputStream class in IO package:
Program 1: Assume the existence of file “c:/demo.txt”.
// Java program to illustrate // BufferedInputStream.close() method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { // Create input stream 'demo.txt' // for reading containing // text "GEEKSFORGEEKS" FileInputStream inputStream = new FileInputStream( "c:/demo.txt" ); // Convert inputStream to // bufferedInputStream BufferedInputStream buffInputStr = new BufferedInputStream(inputStream); // Get the number of bytes available // to read using available() method int rem_byte = buffInputStr.available(); // Number of bytes available is printed System.out.println( "Remaining Byte: " + rem_byte); // Close the file buffInputStr.close(); } } |
Remaining Byte: 13
Program 2: Assume the existence of file “c:/demo.txt”.
// Java program to illustrate // BufferedInputStream.close() method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { try { // create input stream 'demo.txt' // for reading containing // text "GEEKS" FileInputStream inputStream = new FileInputStream( "c:/demo.txt" ); // convert inputStream to // bufferedInputStream BufferedInputStream buffInputStr = new BufferedInputStream( inputStream); // get the number of bytes available // to read using available() method int rem_byte = buffInputStr.available(); // number of bytes available is printed System.out.println(rem_byte); // close the file buffInputStr.close(); // now throws io exception // if available() is invoked // after close() rem_byte = buffInputStr.available(); System.out.println(rem_byte); } catch (IOException e) { // exception occurred. System.out.println( "Error: Sorry 'buffInputStr'" + " is closed" ); } } } |
5 Error: Sorry 'buffInputStr' is closed
References: https://docs.oracle.com/javase/10/docs/api/java/io/BufferedInputStream.html#close()