HomeLanguagesJavaPushbackInputStream mark() method in Java with Examples

PushbackInputStream mark() method in Java with Examples

The mark() method of PushbackInputStream class in Java is used to mark the current position in the input stream. This method does nothing for PushbackInputStream. 

Syntax:

public void mark(int readlimit)

Overrides: This method overrides the mark() method of FilterInputStream class. 

Parameters: This method accepts single parameter readlimit that represents the maximum limit of bytes that can be read before the mark position becomes invalid. 

Return value: This method does not return any value. 

Exceptions: This method does not throw any exception. 

Below programs illustrate mark() method of PushbackInputStream class in IO package: 

Program 1: 

Java




// Java program to illustrate
// PushbackInputStream mark() method
 
import java.io.*;
 
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
 
        // Create an array
        byte[] byteArray
            = new byte[] { 'G', 'E', 'E',
                           'K', 'S' };
 
        // Create inputStream
        InputStream inputStr
            = new ByteArrayInputStream(byteArray);
 
        // Create object of
        // PushbackInputStream
        PushbackInputStream pushbackInputStr
            = new PushbackInputStream(inputStr);
 
        for (int i = 0; i < byteArray.length; i++) {
            // Read the character
            System.out.print(
                (char)pushbackInputStr.read());
        }
 
        // Revoke mark() but it does nothing
        pushbackInputStr.mark(5);
    }
}


Output:

GEEKS

Program 2: 

Java




// Java program to illustrate
// PushbackInputStream mark() method
 
import java.io.*;
 
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
 
        // Create an array
        byte[] byteArray
            = new byte[] { 'H', 'E', 'L',
                           'L', 'O' };
 
        // Create inputStream
        InputStream inputStr
            = new ByteArrayInputStream(byteArray);
 
        // Create object of
        // PushbackInputStream
        PushbackInputStream pushbackInputStr
            = new PushbackInputStream(inputStr);
 
        // Revoke mark()
        pushbackInputStr.mark(1);
 
        for (int i = 0; i < byteArray.length; i++) {
            // Read the character
            System.out.print(
                (char)pushbackInputStr.read());
        }
    }
}


Output:

HELLO

References: https://docs.oracle.com/javase/10/docs/api/java/io/PushbackInputStream.html#mark(int)

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32688 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7057 POSTS0 COMMENTS
Nicole Veronica
12198 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12293 POSTS0 COMMENTS
Shaida Kate Naidoo
7182 POSTS0 COMMENTS
Ted Musemwa
7447 POSTS0 COMMENTS
Thapelo Manthata
7160 POSTS0 COMMENTS
Umr Jansen
7150 POSTS0 COMMENTS