InputStream源码
总结:
- InputStream是一个抽象类,所有字节输入流都要继承该类。
- InputStream定义了对字节输入操作的基本方法,其中read()是抽象方法,需要子类实现。
- read(byte b[], int off, int len)的底层实现是循环调用read()方法。循环调用read()导致I/O访问频繁,限制了性能,大部分的子类都会对其进行重写。
package java.io;
public abstract class InputStream implements Closeable {
//可以跳过的最大的字节数
private static final int MAX_SKIP_BUFFER_SIZE = 2048;
public abstract int read() throws IOException;
public int read(byte b[]) throws IOException {
return read(b, 0, b.length);
}
//可以发现这里一次性读取一个字节数组的底层实现实际是循环调用read();将多次调用I/O
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;
}
//这里先读一个字节再循环,感觉不到什么作用?直接循环不可以吗?
//for (int i=0; i < len ; i++) {
// c = read();
// if (c == -1) {
// break;
// }
// b[off + i] = (byte)c;
// }
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;
}
//跳过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;
}
public int available() throws IOException {
return 0;
}
public void close() throws IOException {}
public synchronized void mark(int readlimit) {}
public synchronized void reset() throws IOException {
throw new IOException("mark/reset not supported");
}
public boolean markSupported() {
return false;
}
}
OutputStream源码:
总结:
- OutputStream是所有字节输出流的父类
- 该类定义了对字节输出操作的基本方法,只要write()需要底层实现。
package java.io;
public abstract class OutputStream implements Closeable, Flushable {
public abstract void write(int b) throws IOException;
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
public void write(byte b[], int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException();
} else if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
}
for (int i = 0 ; i < len ; i++) {
write(b[off + i]);
}
}
public void flush() throws IOException {
}
public void close() throws IOException {
}
}