Reader reset() in Java

reset(): This method is available in the java.io.Reader class of Java.

Syntax:

void java.io.Reader.reset() throws IOException

This method resets the stream.

If the stream has been marked, then attempt to reposition it at the mark.

If the stream has not been marked, then attempt to reset it in some way appropriate to the particular stream, for example by repositioning it to its starting point.

Parameters: NA

Returns: NA

Throws:

1. IOException - If the stream has not been marked,or if the mark has been invalidated, or if the stream does not support reset(), or if some other I/O error occurs

Approach 1: When no exception

Java

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

public class Readerreset {
    public static void main(String[] args) throws IOException {

        Reader reader = new StringReader("HELLO");

        reader.reset();
        System.out.println("Successfully reset");
        reader.close();

    }
}

Output:

Successfully reset


Approach 2: IOException

Java

package com.Reader;

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

public class Readerreset {
    public static void main(String[] args) throws IOException {

        Reader reader = new StringReader("HELLO");

        reader.close();
        reader.reset();
        System.out.println("Successfully reset");

    }
}

Output:

Exception in thread "main" java.io.IOException: Stream closed at java.base/java.io.StringReader.ensureOpen(StringReader.java:56) at java.base/java.io.StringReader.reset(StringReader.java:188) at com.Reader.Readerreset.main(Readerreset.java:13)


Some other methods of Reader

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.

markSupported()This method tells whether this stream supports the mark() operation. 

Reader.nullReader()This method returns a new Reader that reads no characters.

read()This method reads a single character.

read(char[])This method reads characters into an array.

read(CharBuffer)This method attempts to read characters into the specified character buffer.

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.

skip(long)This method skips characters.

transferTo(Writer)This method reads all characters from this reader and writes the characters to the given writer in the order that they are read.

No comments:

Post a Comment