Java中的 BufferedReader reset() 方法及示例
Java中BufferedReader类的reset()方法用于固定或标记上一次标记位置的位置,以便再次读取相同的字节。
句法:
public void reset()
throws IOException
覆盖:它覆盖了Reader类的 reset() 方法。
参数:该方法不接受任何参数。
返回值:该方法不返回任何值。
异常:如果 mark() 方法从未在流上调用或者如果 mark 的值无效,则该方法将引发IOException 。
下面的程序说明了 IO 包中 BufferedReader 类中的 reset() 方法:
程序1:假设文件“c:/demo.txt”存在。
// Java program to illustrate
// BufferedReader reset() method
import java.io.*;
public class GFG {
public static void main(String[] args)
{
// Read the stream 'demo.txt'
// for containing text "GEEKS"
FileReader fileReader
= new FileReader(
"c:/demo.txt");
// Convert fileReader to
// bufferedReader
BufferedReader buffReader
= new BufferedReader(
fileReader);
// Read and print characters
// one by one
System.out.println(
"Char : "
+ (char)buffReader.read());
System.out.println(
"Char : "
+ (char)buffReader.read());
System.out.println(
"Char : "
+ (char)buffReader.read());
// Mark is set on the stream
buffReader.mark(0);
System.out.println(
"Char : "
+ (char)buffReader.read());
// Reset() is invoked
buffReader.reset();
// Read and print characters
System.out.println(
"Char : "
+ (char)buffReader.read());
System.out.println(
"Char : "
+ (char)buffReader.read());
}
}
输出:
Char : G
Char : E
Char : E
Char : K
Char : K
Char : S
程序2:假设文件“c:/demo.txt”存在。
// Java program to illustrate
// BufferedReader reset() method
import java.io.*;
public class GFG {
public static void main(String[] args)
{
// Read the stream 'demo.txt'
// containing text "GEEKSFORGEEKS"
FileReader fileReader
= new FileReader(
"c:/demo.txt");
// Convert fileReader to
// bufferedReader
BufferedReader buffReader
= new BufferedReader(
fileReader);
// Read and print characters
// one by one
System.out.println(
"Char : "
+ (char)buffReader.read());
System.out.println(
"Char : "
+ (char)buffReader.read());
System.out.println(
"Char : "
+ (char)buffReader.read());
System.out.println(
"Char : "
+ (char)buffReader.read());
// Mark is set on the stream
buffReader.mark(0);
System.out.println(
"Char : "
+ (char)buffReader.read());
// Reset() is invoked
buffReader.reset();
// read and print characters
System.out.println(
"Char : "
+ (char)buffReader.read());
System.out.println(
"Char : "
+ (char)buffReader.read());
System.out.println(
"Char : "
+ (char)buffReader.read());
System.out.println(
"Char : "
+ (char)buffReader.read());
}
}
输出:
Char : G
Char : E
Char : E
Char : K
Char : S
Char : S
Char : F
Char : O
Char : R
参考:
https://docs.oracle.com/javase/10/docs/api/java Java()