PushbackInputStream理解

来源:互联网 发布:java md5工具类运用 编辑:程序博客网 时间:2024/05/21 14:04

PushbackInputStream存在的意义就是允许我试探性的读取数据流,如果不是我们想要的则返还回去,之所以能够这样,因为其内部维护了一个pushback buffer缓冲区。构造函数可以指定返回的字节个数,学习这个类的时候联系 C语言中的ungetch函数,下面的这个例子实现了《K&R》P82中那个从文件读取整数的那个功能。以此来更好的理解这个类。代码如下:

package thinkinginjava.io;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.PushbackInputStream;//PushbackInputStream学习实例public class GetIntFromFile {public  int getint(PushbackInputStream input){int c,res=0;try {//跳过空白while((c = input.read()) == ' ');//不是数字,不是+-符号if(!isDigit(c) && c!= -1 && c != '+' && c!= '-'){input.unread(c);return -1;  //读出的不是一个数字}int sign = (c == '-') ?-1:1; //符号if(c == '+' || c == '-')c = input.read();for(res = 0; isDigit(c); c = input.read())res = 10 * res + (c - '0');res *= sign;if(c != -1)input.unread(c);} catch (IOException e) {e.printStackTrace();}return res;}private boolean isDigit(int c) {if(c >= '0' && c <= '9')return true;return false;}public static void main(String[] args) {try {//参数1,代表每次最多回退一个字节PushbackInputStream input = new PushbackInputStream(        new FileInputStream("c:\\input.txt"), 1);System.out.println((new GetIntFromFile().getint(input)));} catch (FileNotFoundException e) {e.printStackTrace();}}}


0 1