Description

On this document we will be showing a java example on how to use the close() method of BufferedInputStream Class. This method closes this input stream and releases any system resources associated with the stream. Once the stream has been closed, further read(), available(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect.

Specified by:

  • close in interface Closeable
  • close in interface AutoCloseable

Overrides:

  • close in class FilterInputStream

Throws:

  • IOException – if an I/O error occurs.

Method Syntax

public void close()
throws IOException

Method Argument

Data Type Parameter Description
N/A N/A N/A

Method Returns

This method returns void.

Compatibility

Requires Java 1.0 and up

Java BufferedInputStream close() Example

Below is a java code demonstrates the use of close() method of BufferedInputStream class. The example presented might be simple however it shows the behaviour of the close().

package com.javatutorialhq.java.examples;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;


/*
 * This example source code demonstrates the use of  
 * close() method of BufferedInputStream class
 */

public class BufferedInputStreamCloseExample {

	public static void main(String[] args) {		
		
		try {
			// initialize an input stream which in this case
			// we are intended to read a file thus 
			// FileInputStream object suits it best
			FileInputStream fis = new FileInputStream("C:javatutorialhq"
					+ "inputtest_file.txt");
			
			// initialize BufferedInputStream object
			BufferedInputStream bufferedStream = new BufferedInputStream(fis);
			
			// wrap the stream to BufferedReader
			BufferedReader br = new BufferedReader(new InputStreamReader(bufferedStream));
			String value;
			while((value=br.readLine())!=null){
				System.out.print(value);
			}			
			
			// close the BufferedInputStream
			bufferedStream.close();
			fis.close();
		} catch (FileNotFoundException e) {
			System.out.println("File does not exists");
		} catch (IOException e) {
			System.out.println("IOException occured");
		}		
		

	}

}

Sample Output

Below is the sample output when you run the above example.

ABCDEabcde