StringReader skip(long) in Java

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

Syntax:

long java.io.StringReader.skip(long ns) throws IOException

This method takes one argument. This method skips the specified number of characters in the stream. Returns the number of characters that were skipped.

Note:

1. The ns parameter may be negative, even though the skip method of the Reader superclass throws an exception in this case.

2. Negative values of ns cause the stream to skip backwards. Negative return values indicate a skip backwards.

3. It is not possible to skip backwards past the beginning of the string.

4. If the entire string has been read or skipped, then this method has no effect and always returns 0.

Parameters: One parameter is required for this method.

ns: The number of characters to skip.

Returns: The number of characters actually skipped.

Throws:

1. IOException - If an I/O error occurs.

Approach 1: When no exception

Java

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

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

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

        long ns = 100;
        try {
            stringReader.skip(ns);
            System.out.println("Successfully skips");
        } catch (IOException e) {
            System.out.println("IOException occurs");
        }

    }
}

Output:

Successfully skips


Approach 2: IOException

Java

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

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

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

        long ns = 100;
        stringReader.close();
        try {
            stringReader.skip(ns);
            System.out.println("Successfully skips");
        } catch (IOException e) {
            System.out.println("IOException occurs");
        }

    }
}

Output:

IOException 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