Java教程-Java ByteArrayInputStream类

Java ByteArrayInputStream类
ByteArrayInputStream由两个单词组成:ByteArray和InputStream。顾名思义,它可用于将字节数组作为输入流进行读取。
Java ByteArrayInputStream类包含一个内部缓冲区,用于将字节数组作为流进行读取。在此流中,数据从字节数组中读取。
ByteArrayInputStream的缓冲区根据数据自动增长。
Java ByteArrayInputStream类声明
让我们看一下Java.io.ByteArrayInputStream类的声明:
public class ByteArrayInputStream extends InputStream
Java ByteArrayInputStream类的构造方法
Constructor | Description |
---|---|
ByteArrayInputStream(byte[] ary) | 创建一个新的字节数组输入流,它使用ary作为其缓冲区数组。 |
ByteArrayInputStream(byte[] ary, int offset, int len) | 创建一个新的字节数组输入流,它使用ary作为其缓冲区数组,可以从数组中读取指定的len 个字节的数据。 |
Java ByteArrayInputStream类的方法
Methods | Description |
---|---|
int available() | 它用于返回可以从输入流中读取的剩余字节数。 |
int read() | 它用于从输入流中读取下一个字节的数据。 |
int read(byte[] ary, int off, int len) | 它用于从输入流中的字节数组中读取最多 len 个字节的数据。 |
boolean markSupported() | 它用于测试输入流的标记和重置方法。 |
long skip(long x) | 它用于从输入流中跳过 x 个字节的输入。 |
void mark(int readAheadLimit) | 它用于设置流中当前标记的位置。 |
void reset() | 它用于重置字节数组的缓冲区。 |
void close() | 它用于关闭 ByteArrayInputStream。 |
Java ByteArrayInputStream示例
让我们看一个简单的例子,使用Java ByteArrayInputStream类将字节数组作为输入流进行读取。
package com.javatpoint;
import java.io.*;
public class ReadExample {
public static void main(String[] args) throws IOException {
byte[] buf = { 35, 36, 37, 38 };
//创建新的字节数组输入流
ByteArrayInputStream byt = new ByteArrayInputStream(buf);
int k = 0;
while ((k = byt.read()) != -1) {
//将字节转换为字符
char ch = (char) k;
System.out.println("ASCII value of Character is:" + k + "; Special character is: " + ch);
}
}
}
输出:
ASCII value of Character is:35; Special character is: #
ASCII value of Character is:36; Special character is: $
ASCII value of Character is:37; Special character is: %
ASCII value of Character is:38; Special character is: &