Java Code Example for BufferedInputStream: close() method

close() method of BufferedInputStream closes the current 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.

[java]
/**********************************************************************************
* Created on Nov, 2004 Copyright(c) https://kodehelp.com All Rights Reserved.
**********************************************************************************/
package com.kodehelp.java.io;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
* @author https://kodehelp.com
*
*/
public class BufferedInputStreamClose {

/**
* @param args
*/
public static void main(String[] args) {

File file = new File(“/file.txt”);
FileInputStream fileInputStream = null;
BufferedInputStream bufferedInputStream = null;
byte[] buffer = new byte[1024];
try
{
//create FileInputStream object
fileInputStream = new FileInputStream(file);

//create BufferedInputStream object
bufferedInputStream = new BufferedInputStream(fileInputStream);
int bytesRead = 0;
while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
String chunk = new String(buffer, 0, bytesRead);
System.out.print(chunk);
}
bufferedInputStream.close();
}catch(FileNotFoundException e){
System.out.println(“File not found” + e);
}catch(IOException ioe){
System.out.println(“Exception while reading the file ” + ioe);
}finally{
//close the BufferedInputStream using close method
try{
if(bufferedInputStream != null)
bufferedInputStream.close();//No effect of this statement as we have already closed line 39.

}catch(IOException ioe){
System.out.println(“Error while closing the stream : ” + ioe);
}
}
}
}

[/java]