Java中的InputStream和OutputStream
做Java技术好几个月了,碰到了很多琐碎细小的技术点,一直没有记录。“勿以善小而不为”,正好今天有点空,先从两个Stream说起。
InputStream vs OutputStream
InputStream用来进行数据读取,而OutputStream用来进行数据写入。接口描述:
public abstract class InputStream implements Closeable { public abstract int read() throws IOException; public int read(byte b[]) throws IOException; public int read(byte b[], int off, int len) throws IOException; public long skip(long n) throws IOException; public void close() throws IOException; public synchronized void mark(int readlimit); public synchronized void reset() throws IOException; //... } public abstract class OutputStream implements Closeable, Flushable { public abstract void write(int b) throws IOException; public void write(byte b[]) throws IOException; public void write(byte b[], int off, int len) throws IOException; public void flush() throws IOException; public void close() throws IOException; }
Close Streams
Java中的Stream是需要通过close方法显式进行关闭的。OutputStream上面还有一个方法叫flush,close方法会自动执行flush。所以在调用close之前无需调用flush方法。
如果一个Stream在构建的时候,通过构造函数传入另外一个Stream,当该Stream被close的时候,原始的Stream也会被关闭,参见如下代码:
OutputStream file = new FileOutputStream( "quarks.ser" ); OutputStream buffer = new BufferedOutputStream( file ); ObjectOutput output = new ObjectOutputStream( buffer ); try{ output.writeObject(quarks); } finally{ output.close(); }
派生类
有时间的话会把每个派生类简单解释一下。