一个ByteArrayInputStream包含一个内部缓冲区包含的字节,可以从流中读取。一个内部计数器跟踪下一个字节是由 read提供的方法。
关闭ByteArrayInputStream没有影响。
继承关系
构造方法
Constructor | Description |
---|---|
ByteArrayInputStream(byte[] buf) | 创建一个 ByteArrayInputStream以便它使用buf作为缓冲数组。 |
ByteArrayInputStream(byte[] buf, int offset, int length) | 创建 ByteArrayInputStream使用 buf作为缓冲数组。 |
成员方法
Method Modifier and Type | Description |
---|---|
int available() | 返回从该输入流读取的剩余字节数(或跳过)。 |
void close() | 关闭 ByteArrayInputStream没有影响。 |
void mark(int readAheadLimit) | 在流中设置当前标记位置。 |
boolean markSupported() | 如果这个测试 InputStream支持马克/复位。 |
int read() | 从这个输入流读取下一个数据字节。 |
int read(byte[] b, int off, int len) | 读到 len数据从输入流中的字节数组的字节。 |
void reset() | 重置缓存到标记的位置。 |
long skip(long n) | 跳过 n字节的输入从输入流。 |
我们发现ByteArrayInputStream对close的实现是空的,这是为了保证封装的统一性,可见close操作没有发生任何行为,因此字节流没有必要手动释放资源
测试示例代码如下:
package cn.yzy.io;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
/*
* 字节数组输入流
*/
public class testByteArrayInputStream {
public static void main(String[] args) {
//源头:创建字节数组
byte[] src = "talk is cheap, show me the code!".getBytes();
//选择流
InputStream is = null;
try {
is = new ByteArrayInputStream(src);
//操作分段读取
byte[] flush = new byte[5];
//接收长度
int len = -1;
while((len = is.read(flush)) != -1) {
String str = new String(flush, 0, len);
System.out.println(str);
}
}catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}finally {
//字节流可以不用主动释放资源,有垃圾回收机制起作用
try {
if(null != is)
is.close();
}catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}