ByteArrayInputStream是字节数组输入流,继承于InputStream。它包含了一个内部缓冲区,该缓冲区包含从流中读取的字节,其实内部缓冲区就是一个字节数组,而ByteArrayInputStream本质就是通过字节数组来实现的。

ByteArrayInputStream的主要函数列表:

public ByteArrayInputStream(byte buf[])
public ByteArrayInputStream(byte buf[], int offset, int length)
public synchronized int read()
public synchronized int read(byte b[], int off, int len)
public synchronized long skip(long n)
public synchronized int available()
public boolean markSupported()
public void mark(int readAheadLimit)
public synchronized void reset()
public void close()

ByteArrayInputStream示例代码:

public class Hello {

    private static final int LEN = 5;
    // 对应英文字母“abcddefghijklmnopqrsttuvwxyz”
    private static final byte[] ArrayLetters = {
    0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
    0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A
    };

    public static void main(String[] args) {
        String tmp = new String(ArrayLetters);
        System.out.println("ArrayLetters="+tmp);

        tesByteArrayInputStream() ;
    }

    /**
     * ByteArrayInputStream的API测试函数
    */
    private static void tesByteArrayInputStream() {
        // 创建ByteArrayInputStream字节流,内容是ArrayLetters数组
        ByteArrayInputStream bais = new ByteArrayInputStream(ArrayLetters);

        // 从字节流中读取5个字节
        for (int i=0; i<LEN; i++) {
            // 若能继续读取下一个字节,则读取下一个字节
            if (bais.available() >= 0) {
            // 读取“字节流的下一个字节”
            int tmp = bais.read();
            System.out.printf("%d : 0x%s\n", i, Integer.toHexString(tmp));
        }
   }

    // 若“该字节流”不支持标记功能,则直接退出
    if (!bais.markSupported()) {
            System.out.println("make not supported!");
            return ;
    }

    // 标记“字节流中下一个被读取的位置”。即--标记“0x66”,因为因为前面已经读取了5个字节,所以下一个被读取的位置是第6个字节”
        // (01), ByteArrayInputStream类的mark(0)函数中的“参数0”是没有实际意义的。
    // (02), mark()与reset()是配套的,reset()会将“字节流中下一个被读取的位置”重置为“mark()中所保存的位置”
    bais.mark(0);

    // 跳过5个字节。跳过5个字节后,字节流中下一个被读取的值应该是“0x6B”。
    bais.skip(5);

    // 从字节流中读取5个数据。即读取“0x6B, 0x6C, 0x6D, 0x6E, 0x6F”
    byte[] buf = new byte[LEN];
    bais.read(buf, 0, LEN);
    // 将buf转换为String字符串。“0x6B, 0x6C, 0x6D, 0x6E, 0x6F”对应字符是“klmno”
    String str1 = new String(buf);
    System.out.printf("str1=%s\n", str1);

    // 重置“字节流”:即,将“字节流中下一个被读取的位置”重置到“mark()所标记的位置”,即0x66。
    bais.reset();
    // 从“重置后的字节流”中读取5个字节到buf中。即读取“0x66, 0x67, 0x68, 0x69, 0x6A”
    bais.read(buf, 0, LEN);
    // 将buf转换为String字符串。“0x66, 0x67, 0x68, 0x69, 0x6A”对应字符是“fghij”
    String str2 = new String(buf);
    System.out.printf("str2=%s\n", str2);
    }
}
运行结果:
ArrayLetters=abcdefghijklmnopqrstuvwxyz
0 : 0x61
1 : 0x62
2 : 0x63
3 : 0x64
4 : 0x65
str1=klmno
str2=fghij


基于JDK8的ByteArrayInputStream类的源码分析:

public class ByteArrayInputStream extends InputStream {

    //一个字节数组
    protected byte buf[];

    /**
     * The index of the next character to read from the input stream buffer.
     * This value should always be nonnegative
     * and not larger than the value of <code>count</code>.
     * The next byte to be read from the input stream buffer
     * will be <code>buf[pos]</code>.
     */
    //从输人流缓冲区中读取下一个自负的index
    protected int pos;

    /**
     * The currently marked position in the stream.
     * ByteArrayInputStream objects are marked at position zero by
     * default when constructed.  They may be marked at another
     * position within the buffer by the <code>mark()</code> method.
     * The current buffer position is set to this point by the
     * <code>reset()</code> method.
     * <p>
    * If no mark has been set, then the value of mark is the offset
     * passed to the constructor (or 0 if the offset was not supplied).
     *
     * @since   JDK1.1
     */
    //用来标记在流中的当前位置
    protected int mark = 0;

    /**
     * The index one greater than the last valid character in the input
     * stream buffer.
     * This value should always be nonnegative
     * and not larger than the length of <code>buf</code>.
     * It  is one greater than the position of
     * the last byte within <code>buf</code> that
     * can ever be read  from the input stream buffer.
     */
    //下标,比输入流缓冲区中的最后一个有效字符大的
    protected int count;
    //创建一个以buf大小的ByteArrayInputStream
    public ByteArrayInputStream(byte buf[]) {
        this.buf = buf;
        this.pos = 0;
        this.count = buf.length;
    }

    /**
     * Creates <code>ByteArrayInputStream</code>
    * that uses <code>buf</code> as its
     * buffer array. The initial value of <code>pos</code>
    * is <code>offset</code> and the initial value
     * of <code>count</code> is the minimum of <code>offset+length</code>
    * and <code>buf.length</code>.
     * The buffer array is not copied. The buffer's mark is
     * set to the specified offset.
     *
     * @param   buf      the input buffer.
     * @param   offset   the offset in the buffer of the first byte to read.
     * @param   length   the maximum number of bytes to read from the buffer.
     */
    //创建一个ByteArrayInputStream,使用buf作为它的缓冲数组,初始位置是offset,初始值的大小为offset+length和length中的最小值
    public ByteArrayInputStream(byte buf[], int offset, int length) {
        this.buf = buf;
        this.pos = offset;
        this.count = Math.min(offset + length, buf.length);
        this.mark = offset;
    }

    /**
     * Reads the next byte of data from this input stream. The value
     * byte is returned as an <code>int</code> in the range
     * <code>0</code> to <code>255</code>. If no byte is available
     * because the end of the stream has been reached, the value
     * <code>-1</code> is returned.
     * <p>
    * This <code>read</code> method
     * cannot block.
     *
     * @return  the next byte of data, or <code>-1</code> if the end of the
     *          stream has been reached.
     */
    //从输人流中读取下一个字节数据,返回值为0到255,没有值返回-1
    public synchronized int read() {
        return (pos < count) ? (buf[pos++] & 0xff) : -1;
    }

    /**
     * Reads up to <code>len</code> bytes of data into an array of bytes
     * from this input stream.
     * If <code>pos</code> equals <code>count</code>,
     * then <code>-1</code> is returned to indicate
     * end of file. Otherwise, the  number <code>k</code>
    * of bytes read is equal to the smaller of
     * <code>len</code> and <code>count-pos</code>.
     * If <code>k</code> is positive, then bytes
     * <code>buf[pos]</code> through <code>buf[pos+k-1]</code>
    * are copied into <code>b[off]</code>  through
     * <code>b[off+k-1]</code> in the manner performed
     * by <code>System.arraycopy</code>. The
     * value <code>k</code> is added into <code>pos</code>
    * and <code>k</code> is returned.
     * <p>
    * This <code>read</code> method cannot block.
     *
     * @param   b     the buffer into which the data is read.
     * @param   off   the start offset in the destination array <code>b</code>
    * @param   len   the maximum number of bytes read.
     * @return  the total number of bytes read into the buffer, or
     *          <code>-1</code> if there is no more data because the end of
     *          the stream has been reached.
     * @exception  NullPointerException If <code>b</code> is <code>null</code>.
     * @exception  IndexOutOfBoundsException If <code>off</code> is negative,
     * <code>len</code> is negative, or <code>len</code> is greater than
     * <code>b.length - off</code>
    */
    //从输入流b读取len大小,初始位置为off
    public synchronized int read(byte b[], int off, int len) {
        if (b == null) {
            throw new NullPointerException();
        } else if (off < 0 || len < 0 || len > b.length - off) {
            throw new IndexOutOfBoundsException();
        }

        if (pos >= count) {
            return -1;
        }

        int avail = count - pos;
        if (len > avail) {
            len = avail;
        }
        if (len <= 0) {
            return 0;
        }
        System.arraycopy(buf, pos, b, off, len);
        pos += len;
        return len;
    }

    /**
     * Skips <code>n</code> bytes of input from this input stream. Fewer
     * bytes might be skipped if the end of the input stream is reached.
     * The actual number <code>k</code>
     * of bytes to be skipped is equal to the smaller
     * of <code>n</code> and  <code>count-pos</code>.
     * The value <code>k</code> is added into <code>pos</code>
     * and <code>k</code> is returned.
     *
     * @param   n   the number of bytes to be skipped.
     * @return  the actual number of bytes skipped.
     */
    //从输入流中跳过n字节
    public synchronized long skip(long n) {
        long k = count - pos;
        if (n < k) {
            k = n < 0 ? 0 : n;
        }

        pos += k;
        return k;
    }

    /**
     * Returns the number of remaining bytes that can be read (or skipped over)
     * from this input stream.
     * <p>
     * The value returned is <code>count - pos</code>,
     * which is the number of bytes remaining to be read from the input buffer.
     *
     * @return  the number of remaining bytes that can be read (or skipped
     *          over) from this input stream without blocking.
     */
    //返回从输入流中可以读取到的数据
    public synchronized int available() {
        return count - pos;
    }

    /**
     * Tests if this <code>InputStream</code> supports mark/reset. The
     * <code>markSupported</code> method of <code>ByteArrayInputStream</code>
     * always returns <code>true</code>.
     *
     * @since   JDK1.1
     */
    //是否支持标记
    public boolean markSupported() {
        return true;
    }

    /**
     * Set the current marked position in the stream.
     * ByteArrayInputStream objects are marked at position zero by
     * default when constructed.  They may be marked at another
     * position within the buffer by this method.
     * <p>
     * If no mark has been set, then the value of the mark is the
     * offset passed to the constructor (or 0 if the offset was not
     * supplied).
     *
     * <p> Note: The <code>readAheadLimit</code> for this class
     *  has no meaning.
     *
     * @since   JDK1.1
     */
    //设置当前的mark标记
    public void mark(int readAheadLimit) {
        mark = pos;
    }

    /**
     * Resets the buffer to the marked position.  The marked position
     * is 0 unless another position was marked or an offset was specified
     * in the constructor.
     */
    //重置buffer到mark位置
    public synchronized void reset() {
        pos = mark;
    }

    /**
     * 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 {
    }

}

Java-IO之ByteArrayInputStream的更多相关文章

  1. java io系列02之 ByteArrayInputStream的简介,源码分析和示例(包括InputStream)

    我们以ByteArrayInputStream,拉开对字节类型的“输入流”的学习序幕.本章,我们会先对ByteArrayInputStream进行介绍,然后深入了解一下它的源码,最后通过示例来掌握它的 ...

  2. 【java】内存流:java.io.ByteArrayInputStream、java.io.ByteArrayOutputStream、java.io.CharArrayReader、java.io.CharArrayWriter

    package 内存流; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java. ...

  3. Java IO流学习总结六:ByteArrayInputStream、ByteArrayOutputStream

    类的继承关系 InputStream |__ ByteArrayInputStream OutputStream |__ ByteArrayOutputStream ByteArrayInputStr ...

  4. java io流 数据流 DataInputStream、DataOutputStream、ByteArrayInputStream、ByteArrayOutputStream

    例子程序: package io; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import ...

  5. java.lang.ClassCastException: java.io.ByteArrayInputStream cannot be cast to java.io.FileInputStream

    今天在做文件上传的时候遇到一个这样的问题 java.lang.ClassCastException: java.io.ByteArrayInputStream cannot be cast to ja ...

  6. Java IO 流-- 字节数组流ByteArrayInPutStream ByteArrayOutPutStream

    字节数组流输于缓冲流,放在jvm内存中,java可以直接操作.我们使用时可以不用关闭,交给GC垃圾回收机制处理. 当然我们为了保持良好习惯和代码一致性也可以加上关闭语句. 当其实我么打开ByteArr ...

  7. Java IO(七)ByteArrayInputStream 和 ByteArrayOutputStream

    Java IO(七)ByteArrayInputStream 和 ByteArrayOutputStream 一.介绍 ByteArrayInputStream 和 ByteArrayOutputSt ...

  8. Java IO之字符流和文件

    前面的博文介绍了字节流,那字符流又是什么流?从字面意思上看,字节流是面向字节的流,字符流是针对unicode编码的字符流,字符的单位一般比字节大,字节可以处理任何数据类型,通常在处理文本文件内容时,字 ...

  9. java IO流详解

    流的概念和作用 学习Java IO,不得不提到的就是JavaIO流. 流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象.即数据在两设备间的传输称为流,流的本质是数据传输,根据数据传输 ...

  10. Java IO流学习总结

    Java流操作有关的类或接口: Java流类图结构: 流的概念和作用 流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象.即数据在两设备间的传输称为流,流的本质是数据传输,根据数据传输 ...

随机推荐

  1. C++标准库之stack

    C++库以提供"模板"为主.所谓模板,是指不必预先制定类型的函数或类.我们可以借助STL(标准模板库 Standard Template Library, STL)提供的高效算法来 ...

  2. 零开始:NetCore项目权限管理系统:定义基本接口和实现

    上一篇讲了基础的框架搭建    地址:http://www.cnblogs.com/fuyu-blog/p/8909779.html 这篇主要讲解SqlSugar   ORM的数据库连接以及建表和接口 ...

  3. 阿里架构师带你深入浅出jvm

    本文跟大家聊聊JVM的内部结构,从组件中的多线程处理,JVM系统线程,局部变量数组等方面进行解析 JVM JVM = 类加载器(classloader) + 执行引擎(execution engine ...

  4. JS基础(二)

    一.JS中的循环结构 循环结构的执行步骤 1.声明循环变量: 2.判断循环条件: 3.执行循环体操作: 4.更新循环变量 然后,循环执行2-4,直到条件不成立时,跳出循环. while循环()中的表达 ...

  5. 更新git源以便安装最新版本

    sudo add-apt-repository ppa:git-core/ppa sudo apt-get update

  6. 一个未排序整数数组,有正负数,重新排列使负数排在正数前面,并且要求不改变原来的正负数之间相对顺序,比如: input: 1,7,-5,9,-12,15 ans: -5,-12,1,7,9,15 要求时

    #include <iostream> using namespace std; void txsort(int* arr, int len) { if (!arr || len == 1 ...

  7. 安卓高级7 vitamio 视频框架 从raw文件下获取文件uri

    vitamio免费的拥有多种解码器 而且容易操作 我们先来看看原生视频播放器的怎么使用 原生的: package qianfeng.com.videoviewdemo; import android. ...

  8. CentOS环境下使用GIT基于Nginx的私服搭建全过程

    阅读本文前你必须预先装好CentOS并且已经安装和配置好Nginx了. 安装GIT私服套件 安装centos6.5-centos7.0 安装nginx yum install -y?git gitwe ...

  9. nginx平台初识(二) 浏览器 HTTP 协议缓存机制详解

    1.缓存的分类 缓存分为服务端侧(server side,比如 Nginx.Apache)和客户端侧(client side,比如 web browser). 服务端缓存又分为 代理服务器缓存 和 反 ...

  10. 通过一个例子了解MapReduce

    写MapReduce程序的步骤: 把问题转化为MapReduce模型: 设置运行参数: 写map类: 写reduce类: 例子:统计单词个数 Map的任务是将内容用" "分开,然后 ...