Java.io.InputStreamReader.close() Method

Advertisements


Description

The java.io.InputStreamReader.close() method closes the input stream reader and invocations to read(), ready(), mark(), reset(), or skip() method on a closed stream will throw IOException.

Declaration

Following is the declaration for java.io.InputStreamReader.close() method:

public void close()

Parameters

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.InputStreamReader.close() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class InputStreamReaderDemo {
   public static void main(String[] args) throws IOException {
      FileInputStream fis = null;
      InputStreamReader isr =null;
      int i;
      char c;
      
      try {
         // new input stream reader is created 
         fis = new FileInputStream("C:/test.txt");
         isr = new InputStreamReader(fis);
         
         // input stream reader is closed
         isr.close();
         System.out.print("close() invoked");
         
         // read() called after closed method
         i=isr.read();
         c=(char)i;
         System.out.println(c);
      
      } catch (Exception e) {
      
         // print error
         System.out.print("The stream is already closed");
      } finally {
         
         // closes the stream and releases resources associated
         if(fis!=null)
            fis.close();
         if(isr!=null)
            isr.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:

ABCDE

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

close() invokedThe stream is already closed



Advertisements
Advertisements