Java Code Example for BufferedInputStream : mark() method

BufferedInputStream mark() method marks the current position in this input stream. A subsequent call to the reset method repositions this stream at the last marked position so that subsequent reads re-read the same bytes.

The readlimit argument tells this input stream to allow that many bytes to be read before the mark position gets invalidated.

Stream marks are intended to be used in situations where you need to read ahead a little to see what’s in the stream.

Below is the java code Example for BufferedInputStream mark() method –

/**********************************************************************************
 * 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 BufferedInputStreamMark {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		BufferedInputStream inputStream = null;
		try{
			inputStream = new BufferedInputStream(new FileInputStream("/TestFile.txt"));
			System.out.println("First Character in Buffer ::"+(char)inputStream.read());
			inputStream.mark(0);
			System.out.println("Next Character in buffer is  : "+(char)inputStream.read());
		    System.out.println("Next Character in buffer is  : "+(char)inputStream.read());
		    System.out.println("Next Character in buffer is  : "+(char)inputStream.read());
		    
		    System.out.println("reset method called");
		    
		    inputStream.reset();
		    
		    System.out.println("Next Character in buffer is  : "+(char)inputStream.read());
		    System.out.println("Next Character in buffer is  : "+(char)inputStream.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(inputStream != null)	
					inputStream.close();
 
			}catch(IOException ioe){
				System.out.println("Error while closing the stream : " + ioe);
			}
		}
	}

}

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.