StringReader mark(int) in Java

mark(int): This method is available in the java.io.StringReader class of Java.

Syntax:

void java.io.StringReader.mark(int readAheadLimit) throws IOException

This method takes one argument. This method marks the present position in the stream. Subsequent calls to reset() will reposition the stream to this point.

Parameters: One parameter is required for this method.

readAheadLimit: Limit on the number of characters that may be read while still preserving the mark.

Returns: NA

Throws:

1. IllegalArgumentException - If readAheadLimit < 0.

2. IOException - If an I/O error occurs

Approach 1: When no exception

Java

import java.io.IOException;
import java.io.StringReader;

public class StringReadermark {
    public static void main(String[] args) {

        String s = "HELLO JAVA";
        StringReader stringReader = new StringReader(s);

        int readAheadLimit = 1;
        try {
            stringReader.mark(readAheadLimit);
            System.out.println("Successfully mark read ahead limit");
        } catch (IOException e) {
            System.out.println("IOException occurs");

        } catch (IllegalArgumentException e) {
            System.out.println("IllegalArgumentException occurs");

        }

    }
}

Output:

Successfully mark read ahead limit


Approach 2: IllegalArgumentException

Java

import java.io.IOException;
import java.io.StringReader;

public class StringReadermark {
    public static void main(String[] args) {

        String s = "HELLO JAVA";
        StringReader stringReader = new StringReader(s);

        int readAheadLimit = -1;
        try {
            stringReader.mark(readAheadLimit);
            System.out.println("Successfully mark read ahead limit");
        } catch (IOException e) {
            System.out.println("IOException occurs");

        } catch (IllegalArgumentException e) {
            System.out.println("IllegalArgumentException occurs");

        }

    }
}

Output:

IllegalArgumentException occurs


Some other methods of StringReader

close()This method closes the stream and releases any system resources associated with it.

mark(int)This method marks the present position in the stream. Subsequent calls to reset() will reposition the stream to this point.

markSupported()This method tells whether this stream supports the mark() operation, which it does.

read()This method reads a single character.

read(char[], int, int)This method reads characters into a portion of an array.

ready()This method tells whether this stream is ready to be read.

reset()This method resets the stream to the most recent mark, or to the beginning of the string if it has never been marked.

skip(long)This method skips the specified number of characters in the stream.

StringReader(String)This method creates a new string reader.

No comments:

Post a Comment