提示
Java IO ByteArrayInputStream 使用示例。@ermo
# ByteArrayInputStream 使用示例
ByteArrayInputStream
是 InputStream
的一个子类,用于将字节数组数据读入程序中。
常用的构造方法有:
public ByteArrayInputStream(byte buf[])
public ByteArrayInputStream(byte buf[], int offset, int length)
ByteArrayInputStream(byte buf[])
用于创建一个字节数组输入流,从 buf[0]
开始读取,读取 buf.lenght
个字节长度。
ByteArrayInputStream(byte buf[], int offset, int length)
用于创建一个字节数组输入流,从 buf[offset]
开始读取数据,读取 length
个长度。
read()
方法常用的重载方法:
public synchronized int read()
public synchronized int read(byte b[], int off, int len)
read()
方法可以从流中读取单个字节,返回值为0~255,读取完毕后将返回-1。
read(byte b[], int off, int len)
方法可以将源数组中的数据拷贝到 b[]
中,同时从 b[off]
开始存入,存储 len
个长度。这里要注意,如果读取长度 len
大于 b[]
的长度,会抛出 IndexOutOfBoundsException
异常。
看一个简单的例子:
/**
* Read bytes from ByteArrayInputStream.
*/
public static void read() {
byte[] array = {1, 2, 3, 4, 5};
try {
System.out.print("Read bytes from input stream: ");
ByteArrayInputStream in = new ByteArrayInputStream(array);
int data;
while ((data = in.read()) != -1) {
System.out.print(data + ", ");
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Main method.
*
* @param args args
*/
public static void main(String[] args) {
read();
}
上例输出:
Read bytes from input stream: 1, 2, 3, 4, 5,
如果是将源数组中的数据拷贝到目标数组,可以这样使用:
/**
* Copy data to dest array.
*/
public static void readLen() {
byte[] array = {1, 2, 3, 4, 5};
byte[] dest = new byte[3];
try {
System.out.println("Read bytes from input stream");
ByteArrayInputStream in = new ByteArrayInputStream(array);
in.read(dest, 0, 3);
in.close();
System.out.println(Arrays.toString(dest));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Main method.
*
* @param args args
*/
public static void main(String[] args) {
readLen();
}
上例会输出以下内容:
[1, 2, 3]
available()
方法返回剩余可读取的字节长度。
/**
* Use available.
*/
public static void available() {
byte[] array = {4, 5, 6, 7, 8, 9};
try {
ByteArrayInputStream in = new ByteArrayInputStream(array);
System.out.println("\nRead bytes begin, available: " + in.available());
in.read();
in.read();
System.out.println("Read bytes end, available: " + in.available());
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Main method.
*
* @param args args
*/
public static void main(String[] args) {
available();
}
上例程序会输出:
Read bytes begin, available: 6
Read bytes end, available: 4
ByteArrayInputStream
还有一些其他方法:
方法 | 描述 |
---|---|
public synchronized long skip(long n) | 跳过当前输入流的 n 个字节 |
public void mark(int readAheadLimit) | 标记已经读取的流的位置,用于重新从这个位置读取流,当需要重新读取时,调用 reset() 方法 |
public synchronized void reset() | 调用 reset() 方法将从 mark() 标记的位置重新读取流 |
public boolean markSupported() | 查询当前类是否支持使用 mark() 重新读取流 |
在 mark(int readAheadLimit)
中的参数 readAheadLimit
表示设置标记后,能够继续往后读取的最大字节数,避免占用过多内存。
在 ByteArrayInputStream
中 readAheadLimit
这个参数无效。