📜  Java中的 PushbackReader reset() 方法及示例

📅  最后修改于: 2022-05-13 01:55:36.329000             🧑  作者: Mango

Java中的 PushbackReader reset() 方法及示例

Java中PushbackReader 类reset()方法用于重置 Stream。对于 PushbackReader,此方法始终会引发异常,因为 PushbackReader 不支持此方法。

句法:

public void reset()

参数:此方法不接受任何参数。

返回值:此方法不返回任何值。

异常:此方法总是抛出 IOException,因为不支持 reset() 方法。

下面的方法说明了 reset() 方法的工作:

方案一:

// Java program to demonstrate
// PushbackReader reset() method
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        try {
            // Initializing a StringReader
            // and PushbackReader
            String s = "GeeksForGeeks";
  
            StringReader stringReader
                = new StringReader(s);
            PushbackReader pushbackReader
                = new PushbackReader(stringReader);
  
            // reset the stream position
            pushbackReader.reset();
  
            // Close the stream using reset()
            pushbackReader.close();
            System.out.println("Stream Closed.");
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
java.io.IOException: mark/reset not supported

方案二:

// Java program to demonstrate
// PushbackReader reset() method
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        try {
            // Initializing a StringReader
            // and PushbackReader
            String s = "GFG";
  
            StringReader stringReader
                = new StringReader(s);
            PushbackReader pushbackReader
                = new PushbackReader(stringReader);
  
            // reset the stream position
            pushbackReader.reset();
  
            // Close the stream
            pushbackReader.close();
            System.out.println("Stream Closed.");
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
java.io.IOException: mark/reset not supported

参考: https://docs.oracle.com/javase/9/docs/api/ Java/io/PushbackReader.html#reset–