一文彻底掌握Java IO类库

本文详细剖析了Java IO类库,包括字节流和字符流两大类,涵盖InputStream、OutputStream、Reader、Writer等核心类的内部方法和常用实现,如BufferedInputStream、FileInputStream、BufferedReader等,帮助开发者彻底掌握Java IO操作。
摘要由CSDN通过智能技术生成

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值