源码剖析之java.io.ByteArrayInputStream

java的数据源有很多,比如:文件、网络、管道、命令行,甚至是内存。
其实我个人认为 java对流的源头概念做了更抽象的扩展,让一些本来很直观的操作,也封装为io流的形式,会增加理解的坡度。

比如: java.io.ByteArrayInputStream 其实完全可以不设计为流的一部分,因为其本质不过是对byte[] 的一个数据读取的处理,即使不用流的概念,完全可以自己实现自己想要的功能。[b] 但是在某些情况下,使用这种流可能和其他的流更好统一交互。所以从这一点看还是有点意义的[/b]

下面就分析java.io.ByteArrayInputStream 的源码实现,因为完全是对byte[]的处理,所以很简单。

另外:[b]数组是java数据结构中常用的底层数据结构。字节流的操作很大程度上是byte[]字节数组的操作 或复制 或移动 或扩展[/b]。



package java.io;

/**
其内部是通过保持一个byte[] 来实现的
*/
public
class ByteArrayInputStream extends InputStream {

protected byte buf[];

/**
* --标志从inputStream读取的下一个字符的索引
* --pos 不能为负值
*--pos 必须不大于 count
* --read方法读取的下一个byte是 buf[pos]
*/
protected int pos;

/**
*-- 当前在stream中 标记的位置
*--初始化时 ByteArrayInputStream 被标记为0
*-- mark(int)方法可以设定mark的值
*/
protected int mark = 0;


protected int count;

/**
* 构造方法需要传递 byte[]数组
*/
public ByteArrayInputStream(byte buf[]) {
this.buf = buf;
this.pos = 0; //当前位置设置为0
this.count = buf.length; //count 设置为buf.length
}

/**
*同上,只是buf 的数组事从offset开始算的
*/
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;
}

/**
* 读下一个字节。可以看到此字节就是buf[pos++]
*/
public synchronized int read() {
return (pos < count) ? (buf[pos++] & 0xff) : -1;
}

/**
* 其覆盖了父类的方法,父类是循环调用read方法
其实read方法就是 buf数组内容 copy 到 b中。
*/
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;
}
if (pos + len > count) {
len = count - pos;
}
if (len <= 0) {
return 0;
}
System.arraycopy(buf, pos, b, off, len); //其实就是数组的复制操作,java对很多底层的操作归根结底,大部分都是对数组的操作。
pos += len;
return len;
}

/**
* 跳过n字节,其实就是对pos的处理,标志当前应该读的下一个字符
*/
public synchronized long skip(long n) {
if (pos + n > count) {
n = count - pos;
}
if (n < 0) {
return 0;
}
pos += n;
return n;
}

/**
*还剩下多少可以读的自己
*/
public synchronized int available() {
return count - pos;
}


public boolean markSupported() {
return true;
}

/**
* 可设置标记
*/
public void mark(int readAheadLimit) {
mark = pos;
}

/**
*重置后讲从最初的位置开始读
*/
public synchronized void reset() {
pos = mark;
}

/**
*ByteArrayInputStream 的close 方法无效
*/
public void close() throws IOException {
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值