回退流
在JAVA IO中所有的数据都是采用顺序的读取方式,即对于一个输入流来讲都是采用从头到尾的顺序读取的,如果在输入流中某个不需要的内容被读取进来,我们就要采取办法把不需要的数据处理掉,为了解决这样的处理问题,在JAVA中提供了一种回退输入流(PushbackInputStream、PushbackReader),可以把读取进来的某些数据重新回退到输入流的缓冲区之中。
回退流主要给我们提供了三种回退方法
- public void unread(int b)throws IOException//推回一个字节:将其复制到推回缓冲区之前。此方法返回后,要读取的下一个字节的值将为 (byte)b。
- public void unread(byte[] b) throws IOException //推回一个 byte 数组:将其复制到推回缓冲区之前。
- public void unread(byte[]b, int off, int len) throws IOException //推回 byte 数组的某一部分:将其复制到推回缓冲区之前
具体可以看一下示例:
public static void main(String[] args) throws IOException {
String s = "abcdefghj";
ByteArrayInputStream bais = new ByteArrayInputStream(s.getBytes());//读取内存字符串
PushbackInputStream pis = new PushbackInputStream(bais,4);//使用指定 size 的推回缓冲区创建 PushbackInputStream
byte[]buffer = new byte[4];存放回退数据
while ((pis.read(buffer))!=-1){
System.out.println(new String(buffer));
if (new String(buffer).equals("abcd")){
pis.unread(buffer,2,2);回退buffer数组从2号位置后两位
buffer = new byte[4];
}
}
输入结果
public static void main(String[] args) throws IOException {
String s = "abcdefghj";
ByteArrayInputStream bais = new ByteArrayInputStream(s.getBytes());
PushbackInputStream pis = new PushbackInputStream(bais,3);
int n;
byte[]buffer = new byte[3];
while ((pis.read(buffer))!=-1){
System.out.println(new String(buffer));
if (new String(buffer).equals("abc")){
pis.unread(new byte[]{'M','N','O'});//返回整个数组
buffer = new byte[3];
}
}
结果:
String s = "www.tulun.com";
ByteArrayInputStream in = new ByteArrayInputStream(s.getBytes());
PushbackInputStream pis = new PushbackInputStream(in);
int n;
while ((n=pis.read())!=-1){//读取内容
if (n=='.'){//判断是否读到'.'
pis.unread(n);
pis.read();
System.out.print(("(退回"+(char)n+")"));
}else{
System.out.print((char)n);
}
}
运行结果: