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

根据文档,

void mark(int readlimit):标记此输入流中的当前位置。PushbackInputStream 的 mark 方法不执行任何操作

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

您可以检查上面的“不执行任何操作”。那么,如果是这种情况,为什么以及在哪里有用?在什么情况下我可以使用以上两种方法?

下面是示例:

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(); 

    } 

上面是示例,但没有得到这两种方法的确切作用。请指导。


偶然的你
浏览 173回答 1
1回答

猛跑小猪

和方法是可选操作,并非每个 InputStreammark都reset需要支持。你可以打电话markSupported询问是否可以。PushbackInputStream 不支持这些方法。这些方法仍然存在,因为它们是在InputStream接口中定义的。也许是一个糟糕的设计决策(可能已添加到单独的界面中),但事实就是如此。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java