Java IO
库中的流表明有能力产出数据的数据源对象或者是有能力接收数据的接收端对象,咱们通常把它分红输入和输出两部分:设计模式
InputStream
或Reader
派生的类都含有名为read
的方法,用于读取单个字节或字节数组。OuputStream
或Writer
派生的类都含有名为write
的方法,用于写入单个字节或字节数组。咱们一般经过叠合多个对象来提供所指望的功能,这实际上是一种装饰器设计模式。数组
InputStream
的做用它的做用是用来表示那些从不一样数据源产生输入的类,而最终结果就是经过read
方法得到数据源的内容,从数据源中读出的内容用int
或byte[]
来表示:bash
String
对象InputStream
源码InputStream
是一个抽象类,全部表示字节输入的流都是继承于它,它实现了如下接口: 网络
public abstract int read() throws IOException
返回输入流的下一个字节(next byte
),若是已经到达输入流的末尾,那么返回-1
public int read(byte b[]) throws IOException
尝试从输入流中读取b.length
长度的字节,存入到b
中,若是已经到达末尾返回-1
,不然返回成功写入到b
中的字节数。public int read(byte b[], int off, int len) throws IOException
尝试从输入流中读取下len
长度的字节,若是len
为0
,那么返回0
,不然返回实际读入的字节数,读入的第一个字节存放在数据b[off]
中,若是没有可读的,那么返回-1
。public long skip(long n) throws IOException
跳过,并丢弃掉n
个字节,其最大值为2048
。InputStream
的具体实现类ByteArrayInputStream
它接收byte[]
做为构造函数的参数,咱们调用read
方法时,就是从byte[]
数组里,读取字节。public ByteArrayInputStream(byte buf[], int offset, int length) {
this.buf = buf;
this.pos = offset;
this.count = Math.min(offset + length, buf.length);
this.mark = offset;
}
public synchronized int read() {
return (pos < count) ? (buf[pos++] & 0xff) : -1;
}
复制代码
StringBufferInputStream
已通过时,推荐使用StringReader
。FileInputStream
FileInputStream
支持提供文件名、File
和FileDescription
做为构造函数的参数,它的read
调用的是底层的native
方法。public FileInputStream(File file) throws FileNotFoundException {
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(name);
}
if (name == null) {
throw new NullPointerException();
}
if (file.isInvalid()) {
throw new FileNotFoundException("Invalid file path");
}
fd = new FileDescriptor();
fd.attach(this);
path = name;
open(name);
}
public int read() throws IOException {
return read0();
}
private native int read0() throws IOException;
复制代码
PipedInputStream
经过通讯管道来交换数据,若是两个线程但愿进行数据的传输,那么它们一个建立管道输出流,另外一个建立管道输入流,它必需要和一个PipedOutputStream
相链接。public PipedInputStream(int pipeSize) {
if (pipeSize <= 0) {
throw new IllegalArgumentException("pipe size " + pipeSize + " too small");
}
buffer = new byte[pipeSize];
}
public PipedInputStream(PipedOutputStream out, int pipeSize) throws IOException {
this(pipeSize);
connect(out);
}
@Override
public synchronized int read() throws IOException {
if (!isConnected) {
throw new IOException("Not connected");
}
if (buffer == null) {
throw new IOException("InputStream is closed");
}
lastReader = Thread.currentThread();
try {
int attempts = 3;
while (in == -1) {
// Are we at end of stream?
if (isClosed) {
return -1;
}
if ((attempts-- <= 0) && lastWriter != null && !lastWriter.isAlive()) {
throw new IOException("Pipe broken");
}
notifyAll();
wait(1000);
}
} catch (InterruptedException e) {
IoUtils.throwInterruptedIoException();
}
int result = buffer[out++] & 0xff;
if (out == buffer.length) {
out = 0;
}
if (out == in) {
in = -1;
out = 0;
}
notifyAll();
return result;
}
复制代码
SequenceInputStream
将多个InputStream
链接在一块儿,一个读完后就完毕,并读下一个,它接收两个InputStream
对象或者一个容纳InputStream
对象的容器Enumeration
。public int read() throws IOException {
while (in != null) {
int c = in.read();
if (c != -1) {
return c;
}
nextStream();
}
return -1;
}
复制代码
ObjectInputStream
它和一个InputStream
相关联,源数据都是来自于这个InputStream
,它继承于InputStream
,而且它和传入的InputStream
并非直接关联的,中间经过了BlockDataInputStream
进行中转,要关注的就是它的readObject
方法,它会把一个以前序列化过的对象进行反序列化,而后获得一个Object
对象,它的目的在于将(把二进制流转换成为对象)和(从某个数据源中读出字节流)这两个操做独立开来,让它们能够随意地组合。public ObjectInputStream(InputStream in) throws IOException {
verifySubclass();
bin = new BlockDataInputStream(in);
handles = new HandleTable(10);
vlist = new ValidationList();
serialFilter = ObjectInputFilter.Config.getSerialFilter();
enableOverride = false;
readStreamHeader();
bin.setBlockDataMode(true);
}
public final Object readObject() throws IOException, ClassNotFoundException {
if (enableOverride) {
return readObjectOverride();
}
// if nested read, passHandle contains handle of enclosing object
int outerHandle = passHandle;
try {
Object obj = readObject0(false);
handles.markDependency(outerHandle, passHandle);
ClassNotFoundException ex = handles.lookupException(passHandle);
if (ex != null) {
throw ex;
}
if (depth == 0) {
vlist.doCallbacks();
}
return obj;
} finally {
passHandle = outerHandle;
if (closed && depth == 0) {
clear();
}
}
}
复制代码
FilterInputStream
它的构造函数参数就是一个InputStream
:protected FilterInputStream(InputStream in) {
this.in = in;
}
public int read() throws IOException {
return in.read();
}
复制代码
这个类很特殊,前面的InputStream
子类都是传入一个数据源(Pipe/byte[]/File
)等等,而后经过重写read
方法从数据源中读取数据,而FilterInputStream
则是将InputStream
组合在内部,它调用in
去执行InputStream
定义的抽象方法,也就是说它不会改变组合在内部的InputStream
所对应的数据源。 另外,它还新增了一些方法,这些方法底层仍是调用了read
方法,可是它封装了一些别的操做,好比DataInputStream
中的readInt
,它调用in
连续读取了四次,而后拼成一个int
型返回给调用者,之因此采用组合,而不是继承,目的是将(把二进制流转换成别的格式)和(从某个数据源中读出字节流)这两个操做独立开来,让它们能够随意地组合。ide
public final int readInt() throws IOException {
int ch1 = in.read();
int ch2 = in.read();
int ch3 = in.read();
int ch4 = in.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
}
复制代码
OuputStream
的做用OuputStream
决定了输出要去往的目标:函数
OutputStream
源码和InputStream
相似,也是一个抽象类,它的子类表明了输出所要去往的目标,它的关键方法以下: ui
write
方法,前两个
write
方法最终都是调用了抽象的
write(int oneByte)
方法,最终怎么写入是由子类实现的。
OutputStream
的具体实现类ByteArrayOutputStream
在ByteArrayOutputStream
的内部,有一个可变长的byte[]
数组,当咱们调用write
方法时,就是向这个数组中写入数据,它还提供了toByteArray/toString
方法,来得到当前内部byte[]
数组中的内容。FileOutputStream
它和上面相似,只不过写入的终点换成了所打开的文件。PipedOutputStream
和PipedInputStream
相关联。ObjectOutputStream
和ObjectInputStream
相似,只不过它内部组合的是一个OutputStream
,当调用writeObject(Object object)
方法时,实际上是先将Object
进行反序列化转换为byte
,再输出到OuputStream
所指向的目的地。FilterOutputStream
它的思想和FilterInputStream
相似,都是在内部组合了一个OuputStream
,FilterOutputStream
提供了写入int/long/short
的write
重载函数,当咱们调用这些函数以后,FilterOutputStream
最终会经过内部的OuputStream
向它所指向的目的地写入字节。