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

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

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

Java IO _回退流

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

Java IO _回退流

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

Java IO _回退流

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

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

  1. importjava.io.ByteArrayInputStream;
  2. importjava.io.PushbackInputStream;
  3. publicclassPushInputStreamDemo{
  4. publicstaticvoidmain(Stringargs[])throwsException{//所有异常抛出
  5. Stringstr="www.mldnjava.cn";//定义字符串
  6. PushbackInputStreampush=null;//定义回退流对象
  7. ByteArrayInputStreambai=null;//定义内存输入流
  8. bai=newByteArrayInputStream(str.getBytes());//实例化内存输入流
  9. 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. };

相关文章:

  • 2021-06-17
  • 2021-06-05
  • 2021-10-19
猜你喜欢
  • 2021-10-19
  • 2022-01-10
  • 2021-09-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-11
相关资源
相似解决方案