ByteArrayInputStream
类用于将内存中的缓冲区用作为InputStream
。输入源是一个字节数组。
ByteArrayInputStream
类提供以下构造函数。
编号 | 方法 | 描述 |
---|---|---|
1 | ByteArrayInputStream(byte [] a) |
此构造函数接受字节数组作为参数。 |
2 | ByteArrayInputStream(byte [] a, int off, int len) |
此构造函数采用一个字节数组和两个整数值,其中off 是要读取的第一个字节,len 是要读取的字节数。 |
当创建了ByteArrayInputStream
对象,就可以使用一些它的辅助方法来读取流或在流上执行其他操作。
编号 | 方法 | 描述 |
---|---|---|
1 | public int read() |
此方法从InputStream 读取下一个数据字节。 返回一个int 值作为数据的下一个字节。 如果它是文件的结尾,则返回-1 。 |
2 | public int read(byte[] r, int off, int len) |
此方法读取从输入流关闭到数组的最多len 个字节数。返回读取的总字节数。如果它是文件的结尾,则返回-1 。 |
3 | public int available() |
给出可以从此文件输入流中读取的字节数。 返回一个int 值,它给出了要读取的字节数。 |
4 | public void mark(int read) |
这将设置流中当前标记的位置。 该参数给出了在标记位置变为无效之前可以读取的最大字节数限制。 |
5 | public long skip(long n) |
从流中跳过n 个字节,它将返回实际跳过的字节数。 |
示例
以下是演示ByteArrayInputStream
和ByteArrayOutputStream
的示例。
import java.io.*;
public class ByteStreamTest {
public static void main(String args[])throws IOException {
ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);
while( bOutput.size()!= 10 ) {
// 获取用户的输入
bOutput.write("hello".getBytes());
}
byte b [] = bOutput.toByteArray();
System.out.println("Print the content");
for(int x = 0 ; x < b.length; x++) {
// 打印字符
System.out.print((char)b[x] + " ");
}
System.out.println(" ");
int c;
ByteArrayInputStream bInput = new ByteArrayInputStream(b);
System.out.println("将字母转为大写 >" );
for(int y = 0 ; y < 1; y++) {
while(( c = bInput.read())!= -1) {
System.out.println(Character.toUpperCase((char)c));
}
bInput.reset();
}
}
}
执行上面示例代码,得到以下结果:
Print the content
h e l l o h e l l o
将字母转为大写 >
H
E
L
L
O
H
E
L
L
O
上一篇:
Java文件和输入和输出(I/O)
下一篇:
Java快速入门