Java.io.InputStream.close() Method



Description

The java.io.InputStream.close() method closes this stream and releases any system resources associated with the stream.

Declaration

Following is the declaration for java.io.InputStream.close() method −

public void close()

Parameters

NA

Return Value

The method does not return any value

Exception

IOException − If an I/O error occurs.

Example

The following example shows the usage of java.io.InputStream.close() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.InputStream;

public class InputStreamDemo {
   public static void main(String[] args) throws Exception {
      InputStream is = null;
      int i = 0;
            
      try {
         // new input stream created
         is = new FileInputStream("C://test.txt");
         
         // invoke available
         i = is.available();
               
         // number of bytes available is printed
         System.out.println(i);
             
         // releases any system resources associated with the stream
         is.close();
            
         // throws io exception on available() invocation
         i = is.available();
         System.out.println(i);
           
      } catch(Exception e) {
         // if any I/O error occurs
         System.out.print("Sorry, the input stream is closed");
      } finally {
         // releases system resources associated with this stream
         if(is!=null)
            is.close();
      }
   }
}

Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program −

ABCDEF

Let us compile and run the above program, this will produce the following result −

6
Sorry, the input stream is closed
java_io_inputstream.htm
Advertisements