一、InputStream
所有字节输入的父类,是一个抽象类。
public abstract int read() throws IOException
从流中读取下一个字节的数据,返回的数据是int类型的范围在0~255之间,如果流中没有数据,将会返回-1,这个方法将会阻塞直到流中有数据可用,这是一个抽象方法,子类必须提供方法的实现。
public int read(byte b[]) throws IOException {
return read(b, 0, b.length);
}
这个方法从流中读取一定数量的字节并且保存在b[]中,而着一定数量就是实际锁读取字节的数量,继续看看read(byte b[], int off, int len)
方法。
public int read(byte b[], int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException();
} else if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
int c = read();//具体有子类实现
if (c == -1) {//结束位置
return -1;
}
b[off] = (byte)c;
int i = 1;
try {
//从流中读取数据到数组中,直到流结束位置
for (; i < len ; i++) {
c = read();
if (c == -1) {
break;
}
b[off + i] = (byte)c;
}
} catch (IOException ee) {
}
return i;//返回读取的位置
}
public long skip(long n) throws IOException
跳过并且从流中丢弃n个字节数据
public long skip(long n) throws IOException {
long remaining = n;
int nr;
if (n <= 0) {
return 0;
}
int size = (int)Math.min(MAX_SKIP_BUFFER_SIZE, remaining);
byte[] skipBuffer = new byte[size];//保存丢弃的字节数据
while (remaining > 0) {
nr = read(skipBuffer, 0, (int)Math.min(size, remaining));
if (nr < 0) {
break;
}
remaining -= nr;
}
return n - remaining;
}
available统计流中字节长度
public int available() throws IOException {
return 0;
}
是否支持标记,默认是不支持标记
public boolean markSupported() {
return false;
}
同时,InputStream的设计者也对并发进行了控制,可以看下面列举的方法。
public synchronized void mark(int readlimit) {}//标记读取的位置,并没有实现,让子类进行实现
public synchronized void reset() throws IOException {//让子类实现
throw new IOException("mark/reset not supported");
}
二、ByteArrayInputStream
内部有一个字节数组缓冲区来保存从流中读取的数据,该类继承InputStream,同时也重写了InputStream中的方法,下面来看看方法
1.available()返回流的长度,也采用了同步的方式
public synchronized int available() {
return count - pos;//count表示总数,pos下个将读取的位置
}
2.read()从流中读取下一个字节,将返回一个int范围在0~255,没有将会返回-1,同时也采用了同步。
public synchronized int read() {
return (pos < count) ? (buf[pos++] & 0xff) : -1;
}
3.reset()重置方法
public synchronized void reset() {
pos = mark;
}
总结
由于之前在学习java并发方面的知识,现在发现io部分也考虑了并发的情况,让我感觉java的知识体系的各个知识互相关联。