Java Code for BufferedInputStream : reset() Method Example

BufferedInputStream reset() method repositions the current stream to the position at the time the mark method was called last time on this input stream.

If markpos is -1 (no mark has been set or the mark has been invalidated), an IOException is thrown. Otherwise, pos is set equal to markpos.

Overrides: reset in class FilterInputStream
Throws: IOException – if this stream has not been marked or, if the mark has been invalidated, or the stream has been closed by
invoking its close() method, or an I/O error occurs.

[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.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

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

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
BufferedInputStream bufferedInputStream = null;
try{
bufferedInputStream = new BufferedInputStream(new FileInputStream(“/test.txt”));
System.out.println(“First Character in Buffer ::”+(char)bufferedInputStream.read());
bufferedInputStream.mark(0);
System.out.println(“Next Character in buffer is : “+(char)bufferedInputStream.read());
System.out.println(“Next Character in buffer is : “+(char)bufferedInputStream.read());
System.out.println(“Next Character in buffer is : “+(char)bufferedInputStream.read());

System.out.println(“reset method called”);

bufferedInputStream.reset();

System.out.println(“Next Character in buffer is : “+(char)bufferedInputStream.read());
System.out.println(“Next Character in buffer is : “+(char)bufferedInputStream.read());

}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();

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

}
[/java]