PushBackInputStream



回退流

在JAVA IO中所有的数据都是采用顺序的读取方式,即对于一个输入流来讲都是采用从头到尾的顺序读取的,如果在输入流中某个不需要的内容被读取进来,则只能通过程序将这些不需要的内容处理掉,为了解决这样的处理问题,在JAVA中提供了一种回退输入流(PushbackInputStream、PushbackReader),可以把读取进来的某些数据重新回退到输入流的缓冲区之中。

使用InputStream要使用read()方法不断读取,是采用顺序的读取方式。

PushbackInputStream类的常用方法

1、public PushbackInputStream(InputStream in) 构造方法 将输入流放入到回退流之中。
2、public int read() throws IOException   普通  读取数据。
3、public int read(byte[] b,int off,int len) throws IOException 普通方法 读取指定范围的数据。
4、public void unread(int b) throws IOException 普通方法 回退一个数据到缓冲区前面。
5、public void unread(byte[] b) throws IOException 普通方法 回退一组数据到缓冲区前面。
6、public void unread(byte[] b,int off,int len) throws IOException 普通方法 回退指定范围的一组数据到缓冲区前面。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`PushbackInputStream` 是Java IO库中的一个类,它提供了一种在读取输入流时将数据“推回”流中的方法,从而可以重新读取该数据。具体来说,`PushbackInputStream` 允许您在读取输入流时将最近读取的字节推回到流中,以便稍后再次读取它们。 例如,如果您正在读取一个文本文件,并且意外地读取了一些不是文本的字节,您可以使用 `PushbackInputStream` 将这些字节推回到流中,然后重新读取它们。 以下是一个示例代码片段,演示如何使用 `PushbackInputStream`: ```java import java.io.*; public class PushbackInputStreamExample { public static void main(String[] args) throws IOException { String str = "Hello, world!"; ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes()); PushbackInputStream pbis = new PushbackInputStream(bais); int b = pbis.read(); System.out.println((char) b); // Output: H pbis.unread(b); // push back the first byte read b = pbis.read(); // read the first byte again System.out.println((char) b); // Output: H byte[] buf = new byte[5]; pbis.read(buf); System.out.println(new String(buf)); // Output: "ello," pbis.unread(buf); // push back the five bytes read byte[] buf2 = new byte[5]; pbis.read(buf2); System.out.println(new String(buf2)); // Output: "ello," } } ``` 在这个示例中,我们首先将字符串 "Hello, world!" 转换为一个字节数组,然后使用 `ByteArrayInputStream` 将其包装为一个输入流。接下来,我们使用 `PushbackInputStream` 包装这个输入流。 我们首先读取第一个字节并将其输出。然后,我们使用 `unread` 方法将该字节推回流中,并再次读取它。然后,我们读取五个字节,并使用 `unread` 方法将它们推回流中。最后,我们再次读取五个字节,这次从流中读取了之前推回的字节。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值