Java CharArrayReader reset()方法及示例
Java中CharArrayReader类的reset()方法是用来重置流的。重置后,如果流已经被标记,那么该方法将尝试在标记处重新定位,否则它将尝试将其定位到起点。
语法。
public void reset()
参数。此方法不接受任何参数。
返回值。此方法不返回任何值。
异常。该方法会抛出IOException。
- 如果在输入输出时发生一些错误
- 如果流还没有被标记
- 如果标记已被废止
- 如果reset()方法不被支持。
下面的方法说明了reset()方法的工作。
程序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??
计划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
参考资料: https://docs.oracle.com/javase/9/docs/api/java/io/CharArrayReader.html#reset-