美文网首页JDK源码系列
JDK源码-InputStream系列

JDK源码-InputStream系列

作者: 薛云龙 | 来源:发表于2017-08-22 10:35 被阅读21次

byte

了解InputStream前,我们先了解下byte.

  • byte存在的意义:
    byte,字节,java中一种基本类型.通常在读取非文本文件(图片,声音,可执行文件,网络通信的数据)需要通过字节数组来保存文件中的内容.
    一个byte占用了8个bit位,所以byte的取值范围为-128到127.
    内存的最小单元是字节,Intel的X86的芯片内存地址是通过字节编的,指针可以指向的最小内存单元就是一个字节,16位的机器是两个字节,32位的机器是四个字节.
  • byte的包装类

byte的包装类就是Byte,列举一下常见方法

  • toString(byte b) //静态的,调用了Integer.toString()
  • ByteCache() //不是很懂,也不是静态方法啊
  • parseByte(String s) //超过范围或者不是数字会报:NumberFormatException,调用了Integer.parseInt()
  • valueOf() //把括号里的参数变成Byte对象,超过范围或者不是数字会报:NumberFormatException
  • byteValue() //返回Byte里的byte
  • shortValue() //返回short,代码里加了强转,平时不写是隐式类型转换,jvm实现的。
  • intValue(),longValue() //同上
  • floatValue(),doubleValue() //同上,但是不知道精度是否会丢失【TODO】
  • toString() //源码里调用了Integer.toString,非静态
  • hashCode() //返回这个类的hashCode
  • equals() //直接比byte了,也不用比hashCode了
  • compareTo(Byte anotherByte) //和另外一个Byte比较大小
  • compare(byte x, byte y) //静态方法

InputStream

抽象架构图

InputSteam是所有字节输入流的实现类的基类.它封装了流处理类的基本操作.

缓存区字节数组最大值
private static final int MAX_SKIP_BUFFER_SIZE = 2048;
从输入流中读取数据的下一个字节,返回int
public abstract int read() throws IOException;
从输入流中读取b.length大小的字节,并存储到字节数组b.
public int read(byte b[]) throws IOException {
        return read(b, 0, b.length);
    }

该方法调用了抽象方法:read(),通过该方法获取流中下一个元素.

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;
        }

        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 e) {
        }
        return i;
    }

原始流处理器

接收一个Byte数组对象,或者一个FileDiscriptor对象,一个String对象,或者其他类型的流源对象.
主要一下四种:

ByteArrayInputStream
  • ByteArrayInputStream里的方法基本上都被synchronized关键字修饰,所以它是线程安全的.
  • ByteArrayInputStream底层是一个缓冲字节数组
/**
     * An array of bytes that was provided
     * by the creator of the stream. Elements <code>buf[0]</code>
     * through <code>buf[count-1]</code> are the
     * only bytes that can ever be read from the
     * stream;  element <code>buf[pos]</code> is
     * the next byte to be read.
     */
    protected byte buf[];
  • 一般情况下很少使用ByteArrayInputStream,它存在的意义一方面是扩展了InputStream基类,可以通过它赖操作字节数组,另一方面,相当于是其他所有流的一个中间状态.,用来缓存其他流输入的数据.
  • 关闭一个字节流是没有意义的.
/**
     * Closing a <tt>ByteArrayInputStream</tt> has no effect. The methods in
     * this class can be called after the stream has been closed without
     * generating an <tt>IOException</tt>.
     */
    public void close() throws IOException {
    }
FileInputStream

先了解下一些相关类的实现:JDK源码-File系列

  • FileInputStream用来操作文件流数据,通过构造函数可知,可以通过文件路径,文件对象,文件描述符对象来创建文件输入流对象.
public FileInputStream(String name) throws FileNotFoundException {
        this(name != null ? new File(name) : null);
    }

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 FileInputStream(FileDescriptor fdObj) {
        SecurityManager security = System.getSecurityManager();
        if (fdObj == null) {
            throw new NullPointerException();
        }
        if (security != null) {
            security.checkRead(fdObj);
        }
        fd = fdObj;
        path = null;

        /*
         * FileDescriptor is being shared by streams.
         * Register this stream with FileDescriptor tracker.
         */
        fd.attach(this);
    }
  • FileInputStream的读取操作和打开文件的操作都是调用本地的native方法.
 /**
     * Opens the specified file for reading.
     * @param name the name of the file
     */
    private native void open0(String name) throws FileNotFoundException;

    // wrap native call to allow instrumentation
    /**
     * Opens the specified file for reading.
     * @param name the name of the file
     */
    private void open(String name) throws FileNotFoundException {
        open0(name);
    }

    /**
     * Reads a byte of data from this input stream. This method blocks
     * if no input is yet available.
     *
     * @return     the next byte of data, or <code>-1</code> if the end of the
     *             file is reached.
     * @exception  IOException  if an I/O error occurs.
     */
    public int read() throws IOException {
        return read0();
    }

    private native int read0() throws IOException;
PipedInputStream&PipedOutputStream

PipedInputStream与PipedOutputStream的设计,主要为了实现线程之间可以通过字节流来传输数据,来达到通信.

参考文章:Java流编程实例及代码

StringBufferInputStream

StringBufferInputStream:将一个字符串缓冲区转换为一个输入流。接收一个String对象作为流的源。(JDK帮助文档上说明:已过时。此类未能正确地将字符转换为字节。从JDK1.1开始,从字符串创建流的首选方法是通过StringReader类进行创建。只有字符串中每个字符的低八位可以由此类使用。)

ObjectInputStream/ObjectOutputStream

详见JDK源码-InputStream系列之ObjectOutputStream/ObjectInputStream

链接流处理器

FilterInputStream
  • FilterInputStream主要用于包装一些其他的基本数据的流对象.
  • 该类以及父类,子类的设计对应了装饰者模式.通过FilterInputStream的代理,所有的子类都可以装饰一个InputStream类型的对象.这样,就能够实现所有装饰类之间的互相转换了.
  • FilterInputStream实现了InputStream接口,同样实现了流处理对象的那一套方法.
BufferedInputStream
  • 它存在的意义是给另外的输入流添加功能,例如,提供“缓冲功能”以及支持“mark()标记”和“reset()重置方法”。
  • 它的底层实现是一个内部缓存数组.在读取输入流的时候,它会分批读入到缓冲区,当缓冲区中的数据被读完之后,输入流会再次填充数据缓冲区.

相关文章

网友评论

    本文标题:JDK源码-InputStream系列

    本文链接:https://www.haomeiwen.com/subject/wetnrxtx.html