115.ByteArrayInputStream

一个ByteArrayInputStream包含一个内部缓冲区包含的字节,可以从流中读取。一个内部计数器跟踪下一个字节是由 read提供的方法。
关闭ByteArrayInputStream没有影响。

继承关系
构造方法
ConstructorDescription
ByteArrayInputStream(byte[] buf)创建一个 ByteArrayInputStream以便它使用buf作为缓冲数组。
ByteArrayInputStream(byte[] buf, int offset, int length)创建 ByteArrayInputStream使用 buf作为缓冲数组。
成员方法
Method Modifier and TypeDescription
int available()返回从该输入流读取的剩余字节数(或跳过)。
void close()关闭 ByteArrayInputStream没有影响。
void mark(int readAheadLimit)在流中设置当前标记位置。
boolean markSupported()如果这个测试 InputStream支持马克/复位。
int read()从这个输入流读取下一个数据字节。
int read(byte[] b, int off, int len)读到 len数据从输入流中的字节数组的字节。
void reset()重置缓存到标记的位置。
long skip(long n)跳过 n字节的输入从输入流。

我们发现ByteArrayInputStream对close的实现是空的,这是为了保证封装的统一性,可见close操作没有发生任何行为,因此字节流没有必要手动释放资源

测试示例代码如下:

package cn.yzy.io;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
/*
 * 字节数组输入流
 */
public class testByteArrayInputStream {
	public static void main(String[] args) {
		//源头:创建字节数组
		byte[] src = "talk is cheap, show me the code!".getBytes();
		
		//选择流
		InputStream is = null;
		try {
			is = new ByteArrayInputStream(src);
			//操作分段读取
			byte[] flush = new byte[5];
			//接收长度
			int len = -1;
			while((len = is.read(flush)) != -1) {
				String str = new String(flush, 0, len);
				System.out.println(str);
			}
		}catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			//字节流可以不用主动释放资源,有垃圾回收机制起作用
			try {
				if(null != is)
					is.close();
			}catch (IOException e) {
				// TODO: handle exception
				e.printStackTrace(); 
			}
		}
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值