• InputStream输入字节流


            InputStream是一个抽象类,实现了Closeable接口。InputStream是代表字节输入流的所有类的父类。程序想要定义一个InputStream抽象类的子类,则必须提供(实现)一个返回输入的下一个字节的方法。

            来看看InputStream内部结构:

     下面一个一个地来看这些方法。

    1、close()方法:关闭字节流并释放字节流相关的系统资源

            close方法其实是实现Closeable接口的方法。并且InputStream的close方法是一个空实现。这意味着继承InputStream的子类虽然不是强制性要重写close方法,但还是建议根据业务进行重写。

    1. /**
    2. * Closes this input stream and releases any system resources associated
    3. * with the stream.
    4. *
    5. *

      The close method of InputStream does

    6. * nothing.
    7. *
    8. * @exception IOException if an I/O error occurs.
    9. */
    10. public void close() throws IOException {}

    2、read()方法:读取下一个字节,并返回该字节的ascii码(字节值的十进制表示方式,即ascii码)

            read()方法从输入流中读取下一个字节的数据。返回的字节值是一个1~255区间的int类型值(字节值的十进制整形表示)。如果达到了输入流的末尾没有剩余的字节了。将返回-1。

            该方法将阻塞线程,直到出现以下情况

    1、输入数据可用;

    2、检测到流的结尾;

    3、抛出一个异常

            注意:read()方法是一个抽象方法,即子类必须实现这个方法。

    1. /**
    2. * Reads the next byte of data from the input stream. The value byte is
    3. * returned as an int in the range 0 to
    4. * 255. If no byte is available because the end of the stream
    5. * has been reached, the value -1 is returned. This method
    6. * blocks until input data is available, the end of the stream is detected,
    7. * or an exception is thrown.
    8. *
    9. *

      A subclass must provide an implementation of this method.

    10. *
    11. * @return the next byte of data, or -1 if the end of the
    12. * stream is reached.
    13. * @exception IOException if an I/O error occurs.
    14. */
    15. public abstract int read() throws IOException;

    3、read(byte b[]):读取一些字节并存入字节数组中,返回实际读取字节串长度

            从输入流中读取一些字节,并存储这些字节到缓冲数组b中。实际读取的字节数量以整数的形式返回(即read(byte b[])返回值是实际读取到的字节数量。这也是一个阻塞方法,同read()。

            如果字节数组b的长度为空,则读取不到字节并返回0。否则,将尝试读取至少一个字节。如果由于输入流到达了文件末尾导致没有剩余的字节,将返回-1;否则,至少读取一个字节并存储进数组数组b。

            读取到的第一个字节被存到b[0]位置,下一个字节存入到b[1],以此类推。读取到的这些字节的数量最多等于数组b的长度。设k为实际读取的字节数量,这些字节将被存储到b[0]到b[k-1],而b[k]到b[b.length-1]之间的元素不会被影响。

            read(b)方法和read(b, 0, b.length)作用是一样的。

            可以看到,read(byte b[]) 实际上是调用read(byte b[], int off, int len)

    1. /**
    2. * Reads some number of bytes from the input stream and stores them into
    3. * the buffer array b. The number of bytes actually read is
    4. * returned as an integer. This method blocks until input data is
    5. * available, end of file is detected, or an exception is thrown.
    6. *
    7. *

      If the length of b is zero, then no bytes are read and

    8. * 0 is returned; otherwise, there is an attempt to read at
    9. * least one byte. If no byte is available because the stream is at the
    10. * end of the file, the value -1 is returned; otherwise, at
    11. * least one byte is read and stored into b.
    12. *
    13. *

      The first byte read is stored into element b[0], the

    14. * next one into b[1], and so on. The number of bytes read is,
    15. * at most, equal to the length of b. Let k be the
    16. * number of bytes actually read; these bytes will be stored in elements
    17. * b[0] through b[k-1],
    18. * leaving elements b[k] through
    19. * b[b.length-1] unaffected.
    20. *
    21. *

      The read(b) method for class InputStream

    22. * has the same effect as:
       read(b, 0, b.length) 
    23. *
    24. * @param b the buffer into which the data is read.
    25. * @return the total number of bytes read into the buffer, or
    26. * -1 if there is no more data because the end of
    27. * the stream has been reached.
    28. * @exception IOException If the first byte cannot be read for any reason
    29. * other than the end of the file, if the input stream has been closed, or
    30. * if some other I/O error occurs.
    31. * @exception NullPointerException if b is null.
    32. * @see java.io.InputStream#read(byte[], int, int)
    33. */
    34. public int read(byte b[]) throws IOException {
    35. return read(b, 0, b.length);
    36. }

    4、read(byte b[], int off, int len) 读取一些字节,并存储到字节数组的指定位置,返回实际读取字节串长度

            从输入流中读取最多len个字节数据进字节数组中。该方法尝试读取尽可能和len一样多的字节,但是可能读取到更小数量的字节。该方法返回一个整形数,代表实际读取到的字节数量。

            其实可以直接看代码就能明白其是如何实现的。这个方法时InputStream抽象类的一个核心方法,读取的大部分逻辑都在这里,方法实现比较简单,但是其思想值得借鉴。

            该方法体内部实际还是调用read()抽象方法来进行读取字节(在for循环中一个一个地读取字节)。这种思想很好地降低了代码耦合,它不需要关心是如何实现read()方法的。 在read()方法的基础上增加一系列逻辑就能读取字节数组了。抽象read()方法的具体实现交给子类去完成,抽象类把处理逻辑搭建好,这种思想在很多地方都用得到:比如android中的baseActivity就是在base基类中把逻辑流程都实现好,具体用到的某个方法在子类中实现。这样可以降低代码耦合,并大大地减少了重复代码。

    1. /**
    2. * Reads up to len bytes of data from the input stream into
    3. * an array of bytes. An attempt is made to read as many as
    4. * len bytes, but a smaller number may be read.
    5. * The number of bytes actually read is returned as an integer.
    6. *
    7. *

      This method blocks until input data is available, end of file is

    8. * detected, or an exception is thrown.
    9. *
    10. *

      If len is zero, then no bytes are read and

    11. * 0 is returned; otherwise, there is an attempt to read at
    12. * least one byte. If no byte is available because the stream is at end of
    13. * file, the value -1 is returned; otherwise, at least one
    14. * byte is read and stored into b.
    15. *
    16. *

      The first byte read is stored into element b[off], the

    17. * next one into b[off+1], and so on. The number of bytes read
    18. * is, at most, equal to len. Let k be the number of
    19. * bytes actually read; these bytes will be stored in elements
    20. * b[off] through b[off+k-1],
    21. * leaving elements b[off+k] through
    22. * b[off+len-1] unaffected.
    23. *
    24. *

      In every case, elements b[0] through

    25. * b[off] and elements b[off+len] through
    26. * b[b.length-1] are unaffected.
    27. *
    28. *

      The read(b, off, len) method

    29. * for class InputStream simply calls the method
    30. * read() repeatedly. If the first such call results in an
    31. * IOException, that exception is returned from the call to
    32. * the read(b, off, len) method. If
    33. * any subsequent call to read() results in a
    34. * IOException, the exception is caught and treated as if it
    35. * were end of file; the bytes read up to that point are stored into
    36. * b and the number of bytes read before the exception
    37. * occurred is returned. The default implementation of this method blocks
    38. * until the requested amount of input data len has been read,
    39. * end of file is detected, or an exception is thrown. Subclasses are encouraged
    40. * to provide a more efficient implementation of this method.
    41. *
    42. * @param b the buffer into which the data is read.
    43. * @param off the start offset in array b
    44. * at which the data is written.
    45. * @param len the maximum number of bytes to read.
    46. * @return the total number of bytes read into the buffer, or
    47. * -1 if there is no more data because the end of
    48. * the stream has been reached.
    49. * @exception IOException If the first byte cannot be read for any reason
    50. * other than end of file, or if the input stream has been closed, or if
    51. * some other I/O error occurs.
    52. * @exception NullPointerException If b is null.
    53. * @exception IndexOutOfBoundsException If off is negative,
    54. * len is negative, or len is greater than
    55. * b.length - off
    56. * @see java.io.InputStream#read()
    57. */
    58. public int read(byte b[], int off, int len) throws IOException {
    59. if (b == null) {
    60. throw new NullPointerException();
    61. } else if (off < 0 || len < 0 || len > b.length - off) {
    62. throw new IndexOutOfBoundsException();
    63. } else if (len == 0) {
    64. return 0;
    65. }
    66. int c = read();
    67. if (c == -1) {
    68. return -1;
    69. }
    70. b[off] = (byte)c;
    71. int i = 1;
    72. try {
    73. for (; i < len ; i++) {
    74. c = read(); //返回的是字节值的十进制表示方式,即ascii码值
    75. if (c == -1) {
    76. break;
    77. }
    78. b[off + i] = (byte)c; //c是字节值的十进制表示方法,这里需要转换成字节类型
    79. }
    80. } catch (IOException ee) {
    81. }
    82. return i;
    83. }

    5、skip(long n)方法:跳过并丢弃输入流中的n个字节数据,并返回实际跳过的字节数量

            该方法跳过并丢弃输入流中的n个字节数据。由于一些原因,skip方法可能会跳过一些更小数量的字节,可能是0。这可能由多种情况中的任何一种造成;在跳过n个字节之前到达文件末尾是唯一的可能性

            返回的是实际跳过的字节数量值。如果n是负数,则该方法返回0,并且没有字节被跳过。子类可能以不同方式处理负值。

            类中的skip方法创建一个字节数组,并在之后重复地读取字节进入数组中,直到读取了n个字节,或到达了输入流的末尾。鼓励子类提供一个更高效的实现。比如,该实现可能依赖于seek的能力。

    1. /**
    2. * Skips over and discards n bytes of data from this input
    3. * stream. The skip method may, for a variety of reasons, end
    4. * up skipping over some smaller number of bytes, possibly 0.
    5. * This may result from any of a number of conditions; reaching end of file
    6. * before n bytes have been skipped is only one possibility.
    7. * The actual number of bytes skipped is returned. If {@code n} is
    8. * negative, the {@code skip} method for class {@code InputStream} always
    9. * returns 0, and no bytes are skipped. Subclasses may handle the negative
    10. * value differently.
    11. *
    12. *

      The skip method of this class creates a

    13. * byte array and then repeatedly reads into it until n bytes
    14. * have been read or the end of the stream has been reached. Subclasses are
    15. * encouraged to provide a more efficient implementation of this method.
    16. * For instance, the implementation may depend on the ability to seek.
    17. *
    18. * @param n the number of bytes to be skipped.
    19. * @return the actual number of bytes skipped.
    20. * @exception IOException if the stream does not support seek,
    21. * or if some other I/O error occurs.
    22. */
    23. public long skip(long n) throws IOException {
    24. long remaining = n;
    25. int nr;
    26. if (n <= 0) {
    27. return 0;
    28. }
    29. int size = (int)Math.min(MAX_SKIP_BUFFER_SIZE, remaining);
    30. byte[] skipBuffer = new byte[size];
    31. while (remaining > 0) {
    32. nr = read(skipBuffer, 0, (int)Math.min(size, remaining));
    33. if (nr < 0) {
    34. break;
    35. }
    36. remaining -= nr;
    37. }
    38. return n - remaining;
    39. }

            skip内部具体实现是值得研究一下的。假如输入流中的字节数量大于skip方法的参数n,则可以成功跳过n个字节;相反情况则在循环中nr = read(skipBuffer, 0, (int)Math.min(size, remaining));读取到输入流末尾时将返回-1,此时if判断内部会跳出循环。remaining代表还剩多少个字节没有被跳过,所以返回值为n - remaining。这种情况下,实际返回skip数量值就小于参数n

    6、available()方法:返回输入流中可读或可跳过的字节数量估计值

            在不会被输入流的下一次方法调用阻塞情况下,返回可从此输入流读取(或跳过)的字节数的估计值。下次调用可能是在相同线程或其他线程。一次简单的读取或跳过许多字节将不会被阻塞,但可能读取或跳过更少的字节。

            注意,尽管一些InputStream的实现类将返回输入流中字节数量的总值,但大部分InputStream的实现类却不会这么做。使用此方法的返回值来分配用于保存此流中所有数据的缓冲区永远都是错误的

            如果已经调用过close方法关闭了输入流,则该方法的子类实现可能选择抛出一个IOException(即假如一个输入流已经被close了,再调用该输入流的available()方法将抛出异常)。        

            最后,这个方法应该被子类重写。

    1. /**
    2. * Returns an estimate of the number of bytes that can be read (or
    3. * skipped over) from this input stream without blocking by the next
    4. * invocation of a method for this input stream. The next invocation
    5. * might be the same thread or another thread. A single read or skip of this
    6. * many bytes will not block, but may read or skip fewer bytes.
    7. *
    8. *

      Note that while some implementations of {@code InputStream} will return

    9. * the total number of bytes in the stream, many will not. It is
    10. * never correct to use the return value of this method to allocate
    11. * a buffer intended to hold all data in this stream.
    12. *
    13. *

      A subclass' implementation of this method may choose to throw an

    14. * {@link IOException} if this input stream has been closed by
    15. * invoking the {@link #close()} method.
    16. *
    17. *

      The {@code available} method for class {@code InputStream} always

    18. * returns {@code 0}.
    19. *
    20. *

      This method should be overridden by subclasses.

    21. *
    22. * @return an estimate of the number of bytes that can be read (or skipped
    23. * over) from this input stream without blocking or {@code 0} when
    24. * it reaches the end of the input stream.
    25. * @exception IOException if an I/O error occurs.
    26. */
    27. public int available() throws IOException {
    28. return 0;
    29. }

    7、剩余方法

            mark(int readlimit)、reset()和markSupported()。

  • 相关阅读:
    项目git commit时卡主不良代码:husky让Git检查代码规范化工作
    如何将不同类别信息发送到kafka的不同通道中
    多线程&并发篇---第十六篇
    npm详解
    es6新语法特性+vue2的学习笔记
    [Linux] Linux 自动挂载mount --bind 实现类似目录硬链的效果 (包含ZFS方案)
    JVM内存模型介绍
    react ref获取dom节点
    【中间件篇-Redis缓存数据库02】Redis高级特性和应用(慢查询、Pipeline、事务、Lua)
    艾美捷PEG-2000 DMG解决方案
  • 原文地址:https://blog.csdn.net/liuqinhou/article/details/127835462