The reset() method of CharArrayReader Class in Java is used to reset the stream. After reset, if the stream has been marked, then this method attempts to reposition it at the mark, else it will try to position it to the starting.
Syntax:
public void reset()
Parameters: This method do not accepts any parameter.
Return Value: This method do not returns any value.
Exception: This method throws IOException:
- if some error occurs while input output
- if the stream has not been marked
- if the mark has been invalidated
- if the reset() method is not supported.
Below methods illustrates the working of reset() method:
Program 1:
// Java program to demonstrate // CharArrayReader reset() method import java.io.*; import java.util.*; class GFG { public static void main(String[] args) { try { char [] str = { 'G' , 'e' , 'e' , 'k' , 's' , 'F' , 'o' , 'r' , 'G' , 'e' , 'e' , 'k' , 's' }; // Create a CharArrayReader instance CharArrayReader reader = new CharArrayReader(str); // Get the character // to be read from the stream int ch; // Read the first 10 characters // to this reader using read() method // This will put the str in the stream // till it is read by the reader for ( int i = 0 ; i < 10 ; i++) { ch = reader.read(); System.out.print(( char )ch); } System.out.println(); // mark the stream for // 5 characters using reset() reader.mark( 5 ); // reset the stream position reader.reset(); // Read the 5 characters from marked position // to this reader using read() method for ( int i = 0 ; i < 5 ; i++) { ch = reader.read(); System.out.print(( char )ch); } } catch (Exception e) { System.out.println(e); } } } |
GeeksForGe eks??
Program 2:
// Java program to demonstrate // CharArrayReader reset() method import java.io.*; import java.util.*; class GFG { public static void main(String[] args) { try { char [] str = { 'G' , 'e' , 'e' , 'k' , 's' , 'F' , 'o' , 'r' , 'G' , 'e' , 'e' , 'k' , 's' }; // Create a CharArrayReader instance CharArrayReader reader = new CharArrayReader(str); // Get the character // to be read from the stream int ch; // Read the first 10 characters // to this reader using read() method // This will put the str in the stream // till it is read by the reader for ( int i = 0 ; i < 10 ; i++) { ch = reader.read(); System.out.print(( char )ch); } System.out.println(); // reset the stream position reader.reset(); // Read the 5 characters from marked position // to this reader using read() method for ( int i = 0 ; i < 5 ; i++) { ch = reader.read(); System.out.print(( char )ch); } } catch (Exception e) { System.out.println(e); } } } |
GeeksForGe Geeks
Reference: https://docs.oracle.com/javase/9/docs/api/java/io/CharArrayReader.html#reset–