InputStream的了解与使用
文章目录
InputStream
是一个字节输入流的抽象类,常用到的实现类有:
- BufferedInputStream
- ByteArrayInputStream 字节数组输入流
- DataInputStream
- FilterInputStream
- PushbackInputStream
- FileInputStream 文件输入流
方法
read()
读取下一个字节,字节的值为0-255。如果到了流的最后,则返回-1。该方法会阻塞直到数据可用
read(byte[] b)
读取多个字节,存储到数组b中。如果实际上读取到字节数小于数组b的长度,那么b数组中剩余部分不会受到影响。
read(byte[] b, int off, int len)
尝试读取len个字节到数组b中,第一个字节将会存储到 b[off]
。因为该方法实际读取到的字节数可能会小于 len ,所以需要重复读取。
readNBytes(byte[] b, int off, int len)
读取len个字节到数组b中,第一个字节将会存储到 b[off]
。跟 read(byte[] b, int off, int len)
相比,该方法能确保在没有异常和未读取到流末尾的情况下,能全部读取到len个字节。该方法的实现基于循环调用 read(byte[] b, int off, int len)
方法,直到结束。
skip(long n)
跳过并丢弃n个字节,并返回实际跳过的字节数。
skipNBytes(long n)
跳过并丢弃n个字节,该方法能确保在没有异常和未到流末尾的情况下,能准确跳过n个字节。 [JDK-8214072] InputStream.skipNBytes(long k) to skip exactly k bytes - Java Bug System
available()
返回可读取的剩余的字节数目
close()
关闭流
例子
一个简单的例子,读取 “hello world"中的 “world”
byte[] bytes = "hello world".getBytes(StandardCharsets.UTF_8);
InputStream in = new ByteArrayInputStream(bytes);
//跳过前面的"hello "
int skip = 6;
while (skip > 0) {
long ns = in.skip(skip);
if (ns > 0 && ns <= skip) {
skip -= ns;
} else if (ns == 0 && in.read() != -1) {
skip--;
} else {
throw new IOException("error");
}
}
//读取后面的"world"
int size = 5;
byte[] res = new byte[5];
int read = 0;
while (read < size) {
read += in.read(res, 0, size - read);
}
System.out.println(new String(res));
更简单的方式为:
byte[] bytes = "hello world".getBytes(StandardCharsets.UTF_8);
InputStream in = new ByteArrayInputStream(bytes);
//跳过前面的"hello "
in.skipNBytes(6);
//读取后面的"world"
byte[] res = new byte[5];
in.readNBytes(res,0,5);
System.out.println(new String(res));
文章作者 梧桐碎梦
上次更新 2023-03-19 21:17:54