Java开发过程中经常会用到 Java IO 类库,本文将深入源码,带你彻底掌握 Java IO 类库。
Java IO类图框架
Java IO 类库可以大体划分为字节流和字符流两大类,再根据输入和输出两种情况,可以再分为四小类。所以 大致框架图 如下所示:
如上图,Java 类图并不繁多,而且分类和命名都非常清晰。其中需要重点掌握的类已经加粗展示在图里。
下边我们逐类逐个展开分析整个类库。
字节流
顾名思义,字节流相关类是处理字节类型数据的,而且都是以『Stream』为后缀的类。根据输入输出类型,可以划分为 InputStream 或 OutputStream 的两大类的实现类。
InputStream
先看看内部方法:
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 int available() throws IOException {/***/} public void close() throws IOException {/***/} public synchronized void mark(int readlimit) {/***/} public synchronized void reset() throws IOException {/***/} public boolean markSupported() {/***/}
InputStream 实现了 Closeable 接口,并且内部只有一个抽象方法 read, 所有实现类都强制要求实现该方法。其他方法提供了非常扼要的默认实现,实现类可以酌情覆盖实现。
FileInputStream
在 《深入理解Java文件输入输出流和文件描述符》 我们已经深入探讨过该类。
简单来说,FileInputStream 内部通过文件描述符 FileDescriptor 和系统文件关联起来,并通过 native 方法调用系统 API 读写文件。
FilterInputStream
FilterInputStream 采用装饰器模式,内部包装了一个 InputStream 对象,并且继承了 InputStream 并覆写全部方法,但方法内容都是单纯地调用内部包装的 InputStream 对象。如下:
public class FilterInputStream extends InputStream { protected volatile InputStream in; protected FilterInputStream(InputStream in) { this.in = in; } public int read() throws IOException { return in.read(); } public int read(byte b[]) throws IOException { return read(b, 0, b.length); } public int read(byte b[], int off, int len) throws IOException { return in.read(b, off, len); } public long skip(long n) throws IOException { return in.skip(n); } public int available() throws IOException { return in.available(); } public void close() throws IOException { in.close(); } public synchronized void mark(int readlimit) { in.mark(readlimit); } public synchronized void reset() throws IOException { in.reset(); } public boolean markSup