简述FileInputStream与BufferedInputStream的区别

         FileInputStream,顾名思义,从文件流中读取数据。逐个字节读取,调用read()方法,每次由"字节输入流"对象从磁盘文件中读入一个字节到内存,此方法返回的是读取到的字节的内容,它是一个int类型0-255之间的字节值,读取至文件末尾返回-1。批量读取自建缓冲区,定义byte[]字节数组代表一个缓冲区。

//逐个字节读取方法1 
InputStream in = null;
		
try {
	//创建”字节流输入流”对象
	in = new FileInputStream("E:\\test.txt");
			
	//保存每次读取到字节值
	int data = -1;
			
	while((data = in.read())!= -1) {
		 System.out.print((char)data);
	}
			
} catch (FileNotFoundException e) {
		e.printStackTrace();
} catch (IOException e) {
		e.printStackTrace();
}finally {
	try {
		in.close();
	} catch (IOException e) {
		e.printStackTrace();
	in = null;
	}
}


//逐个字节读取方法2		
//创建”字节流输入流”对象
try (InputStream in = new FileInputStream("E:\\test.txt")) {
    //保存每次读取到字节值
	int data = -1;
						
	while((data = in.read())!= -1) {
		System.out.print((char)data);
	}
} catch (IOException e) {
	e.printStackTrace();
}

//批量读取
try (InputStream in = new FileInputStream("E:\\yuanjiuyuan\\girl.jpg")) {
			
	byte[] buff = new byte[128];
			
	int len = -1;
	while((len = in.read(buff))!= -1) {
		System.out.printf("本次读取的%d个字节:%s",len,Arrays.toString(buff));
	}
} catch (IOException e) {
	 e.printStackTrace();
}

       BufferedInputStream是缓冲输入流,自带缓冲区(默认大小8192个字节),必须配合FileInputStream类进行使用。作用是为另一个输入流添加一些功能,例如,提供缓冲功能。本质是通过一个内部缓冲区数组来实现的,每当缓冲区中的数据读完之后,输入流会再次填充数据缓冲区;如此反复,直到读完输入流的位置。

//带有缓冲区的字节输入流
//缓冲区默认大小8192
//逐个字节读取

try (BufferedInputStream bis = new BufferedInputStream(new 
     FileInputStream("E:\\test.txt"))) {
			
	//从内存的buff缓冲区中读取1个字节
	int data = -1;
			
	while((data = bis.read()) != -1) {
		System.out.println(data);
	}
} catch (IOException e) {
	e.printStackTrace();
}

//批量字节读取

try (BufferedInputStream bis = new BufferedInputStream(new 
     FileInputStream("E:\\test.txt"))) {
			
	//从内存的buff缓冲区中读取1个字节
    byte[] buff = new byte[128];
 	int data = -1;
			
	while((data = bis.read(buff)) != -1) {
		System.out.println(Arrays.toString(buff));
	}
} catch (IOException e) {
	e.printStackTrace();
}

       逐个字节读取,每调用一次read()方法,都会去BufferedInputStream的缓冲区中读取一个字符,缓冲区内容读取完毕后,会一次性fill填充;批量字节读取,每调用一次read(buffData)方法,都会从BufferedInputStream的缓冲区中读取N个字节(N=buffData.length)

       我们知道,从内存中读取数据的速度要比从硬盘读取数据的速度至少快10倍以上。以上就是两者的区别,如有不当之处还请大家多多指正,一起学习,一起进步!

  • 12
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值