java - Java 中的 mark() 和 reset() 方法

标签 java file stream reset pushbackinputstream

根据文档,

void mark(int readlimit): 标记此输入流中的当前位置。 PushbackInputStream 的标记方法什么都不做

void reset():将此流重新定位到上次在此输入流上调用标记方法时的位置。 类 PushbackInputStream 的重置方法除了抛出 IOException 外什么都不做

You can check above 'DOES NOTHING'. So, If this is the case, Why and Where this is useful ? In which situation I can use above both the methods ?

下面是例子:

import java.io.ByteArrayInputStream; 
import java.io.IOException; 
import java.io.PrintWriter; 
import java.io.PushbackInputStream; 
public class PushbackInputStreamDemo  
{ 
    public static void main(String arg[]) throws Exception 
    { 
        PrintWriter pw = new PrintWriter(System.out, true); 
        String str = "GeeksforGeeks a computer science portal "; 
        byte b[] = str.getBytes(); 
        ByteArrayInputStream bout = new ByteArrayInputStream(b); 
        PushbackInputStream push = new PushbackInputStream(bout); 

        int c; 
        while((c=push.read())!=-1) 
        { 
            pw.print((char)c); 
        } 
        pw.println(); 

        // marking the position  
        push.mark(5); 

        // reseting is not supported throw exception 
        push.reset(); 

        pw.close(); 
    } 
} 

Above is the sample, But not getting what exactly both the methods does. Please guide.

最佳答案

markreset 方法是可选操作,并非每个 InputStream 都需要支持。您可以调用 markSupported 来查看它是否支持。

PushbackInputStream 不支持这些方法。

方法仍然存在,因为它们是在InputStream 接口(interface)中定义的。也许是一个糟糕的设计决定(本可以添加到单独的界面),但事实就是如此。

关于java - Java 中的 mark() 和 reset() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58229954/

相关文章:

java - Google App Engine 数据库模型

java - 调用异步函数时自动显示 'loading' 指示符

java - 用户无法关闭的消息对话框

c - 删除文件指针指向的行的内容

google-app-engine - 如何操作谷歌应用引擎数据存储中的文件

java - 如何使用java作为服务器传输音乐?

C++ std::ifstream:检查字符是否留待读取

java - 为什么 readObject 方法必须调用 defaultReadObject 以保持向后和向前兼容性

c# - 如何获取实际(本地化)的文件夹名称?

Java帮助(文件流)