Java 缓冲流 buffer 的用途和原理是什么?
# Java 缓冲流 buffer 的用途和原理是什么?
buffer本质是一个字节数组(ByteBuff),同时提供数据的结构化访问以及维护读写位置。
而运用BufferedInputStream,则可以一次性读n个字节到内存中的缓冲区,这样在内存中读取数据会快很多。
1.流是单向的 所以会有输入流、输出流
2.字节流一般用于处理文件、视频、音频等,字符流一般用于处理文本数据。
3.原理:维护一个数组、一个指针
public class BufferedInputStream extends FilterInputStream{
private static int DEFAULT_BUFFER_SIZE = 8192;
private static int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8;
// 缓冲数组
protected volatile byte buf[];
// bufUpdater提供buf的compareAndSet方法,这是必要的,因为close()可以是异步的,可以将buf是否为null作为是否close的主要指标。
private static final AtomicReferenceFieldUpdater<BufferedInputStream, byte[]> bufUpdater =
AtomicReferenceFieldUpdater.newUpdater(BufferedInputStream.class, byte[].class, "buf");
// buf中的有效字节数
protected int count;
// buf中的当前字节位置
protected int pos;
public BufferedInputStream(InputStream in) {
this(in, DEFAULT_BUFFER_SIZE);
}
public BufferedInputStream(InputStream in, int size) {
super(in);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
}
//读方法 -> 数据写入到数组buf中
public synchronized int read() throws IOException {
// 当读完buf中的数据后,就需要把InputStream的数据重新填充到buf
if (pos >= count) {
fill();
if (pos >= count)
return -1;
}
// 返回buf的下一个字节 指针后移
return getBufIfOpen()[pos++] & 0xff;
}
}
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
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
编辑 (opens new window)
上次更新: 2022/05/19, 21:26:01