---
title: "Java IO _回退流"
author: "wxyfighting"
date: "2013-06-09T17:34:00Z"
tags: []
slug: "java-io"
draft: false
lastmod: "2013-06-12T14:34:21Z"
id: 1885661
url: "https://wxyfighting.iteye.com/blog/1885661"
---

**1.掌握回退流的工作原理**

**2.使用PushbackInputStream 类完成回退操作**

回退：给了用户第二次读的机会。

![](http://hi.csdn.net/attachment/201108/25/0_1314274907Yb0W.gif)

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

![](http://hi.csdn.net/attachment/201108/25/0_1314274983x74u.gif)

回退操作同样分为字节流和字符流，本教程还是以字节流为准。

![](http://hi.csdn.net/attachment/201108/25/0_1314275092UIww.gif)

对于回退操作来说，提供了三个unread() 的操作方法，这三个操作方法与InputStream 类中的read() 方法是一一对应的。

内存中使用ByteArrayInputStream, 把内容设置到内存之中。

**\[java]**[view plain](http://blog.csdn.net/hanshileiai/article/details/6719647 "view plain")[copy](http://blog.csdn.net/hanshileiai/article/details/6719647 "copy")

01. importjava.io.ByteArrayInputStream;
02. importjava.io.PushbackInputStream;
03. publicclassPushInputStreamDemo{
04. publicstaticvoidmain(Stringargs\[])throwsException{//所有异常抛出
05. Stringstr="www.mldnjava.cn";//定义字符串
06. PushbackInputStreampush=null;//定义回退流对象
07. ByteArrayInputStreambai=null;//定义内存输入流
08. bai=newByteArrayInputStream(str.getBytes());//实例化内存输入流
09. push=newPushbackInputStream(bai);//从内存中读取数据
10. System.out.print("读取之后的数据为：");
11. inttemp=0;
12. while((temp=push.read())!=-1){//读取内容
13. if(temp=='.'){//判断是否读取到了“.”
14. push.unread(temp);//放回到缓冲区之中
15. temp=push.read();//再读一遍
16. System.out.print("（退回"+(char)temp+"）");
17. }else{
18. System.out.print((char)temp);//输出内容
19. }
20. }
21. }
22. };