Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Java ByteArrayInputStream mark() Method

In this tutorial, we will learn about the mark(int readAheadLimit) method of the ByteArrayInputStream class in Java. This method is used to set the position in the Stream which is marked currently. By default, the mark ByteArrayInputStream is marked at zero position. If no mark has been set, then the value of the mark is the offset passed to the constructor.

Syntax:

This is the syntax declaration of this method. It accepts the maximum limit of bytes that can be read before the mark position becomes invalid and doesn't return any value.

public void mark(int readAheadLimit)

Example 2: ByteArrayInputStream mark() Method

Here, we are marking the position in a stream using the mark() method so that we can later retrieve the same position and start reading from this point.

import java.io.ByteArrayInputStream;
import java.io.IOException;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{ 
		byte[] buf = { 1, 2, 3, 4, 5 }; 
		  
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buf); 

        System.out.println(byteArrayInputStream.read()); 
        System.out.println(byteArrayInputStream.read()); 
        System.out.println(byteArrayInputStream.read()); 
  
        System.out.println("Mark() called"); 
        byteArrayInputStream.mark(0); 
        System.out.println(byteArrayInputStream.read()); 
        System.out.println(byteArrayInputStream.read()); 
	}  
}


1
2
3
Mark() called
4
5

Example 2: ByteArrayInputStream mark() Method

When we call the mark() method it marks the position in a stream and when we invoke the reset() method then this we start reading data from the recently marked position in the stream.

import java.io.ByteArrayInputStream;
import java.io.IOException;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{ 
		byte[] buf = { 1, 2, 3 }; 

		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buf); 

		System.out.println(byteArrayInputStream.read()); 

		System.out.println("Mark() method called"); 

		byteArrayInputStream.mark(3); 
		System.out.println(byteArrayInputStream.read()); 
		System.out.println(byteArrayInputStream.read()); 
	}  
}


1
Mark() method called
2
3

mail Conclusion:

In this tutorial, we learned about the mark(int readAheadLimit) method of the ByteArrayInputStream class in Java, which is used to set the current mark position in the stream. By default, it is marked at position 0, when constructed initially.