InputStream的了解与使用

InputStream 是一个字节输入流的抽象类,常用到的实现类有:

  1. BufferedInputStream
  2. ByteArrayInputStream 字节数组输入流
  3. DataInputStream
  4. FilterInputStream
  5. PushbackInputStream
  6. 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));

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值