Java.io之PushbackInputStream

缓存的新应用之一就是回推(pushback)的实现。回推用于输入流,以允许读取字节,然后再将它们返回(回推)到流中。PushbackInputStream类实现了这一思想,提供了一种机制,可以“偷窥”来自输入流的内容而不对它们进行破坏,使用场景比如读取含有特定分隔符的长句子时,可以在读取到分隔符时回推,下一次读取依然可以读取到这次回推掉的字节。

PushbackInputStream用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package cn.deepblog;

import java.io.*;
import java.util.ArrayList;

public class IOSourceCode7 {

public static void main(String[] args) throws IOException {

File file = new File("/Users/deep/Desktop/file.txt");

file.createNewFile();

BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(file));

//非0序列 利用PushbackInputStream将非数字替换未0
bout.write("167a256".getBytes());

bout.flush();

bout.close();

PushbackInputStream pbin = new PushbackInputStream(new FileInputStream(file));

ArrayList<Integer> res = new ArrayList<>();

int r;

while (pbin.available() > 0){

r = pbin.read();
//字符0-9的int值: 48-57
if(r > 57 || r < 48){
pbin.unread(48);

} else {

res.add(r - 48);
}
}

for(int num : res){
System.out.print(num + " ");
}
}
}

控制台输出:
1 6 7 0 2 5 6

unread()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void unread(int b) throws IOException {
ensureOpen();
if (pos == 0) {
throw new IOException("Push back buffer is full");
}
buf[--pos] = (byte)b;
}

public void unread(byte[] b, int off, int len) throws IOException {
ensureOpen();
if (len > pos) {
throw new IOException("Push back buffer is full");
}
pos -= len;
System.arraycopy(b, off, buf, pos, len);
}

不支持mark()

1
2
3
4
5
6
7
8
9
10
public boolean markSupported() {
return false;
}

public synchronized void mark(int readlimit) {
}

public synchronized void reset() throws IOException {
throw new IOException("mark/reset not supported");
}
Donate here.