java IO--字节缓冲流

/**
 * ClassName: 字节缓存流
 * 为了解决在写入文件操作时,频繁的操作文件所带来的性能降低的问题
 * BufferedOutputStream 内部默认的缓存大小时8kb,每次写入时存储到的缓存中的byte数组中,当数组存满 时,会把数组中的数据写入文件,
 * 并且缓存下标归零
 * @Description: TODO
 * @author cai
 * @date 2018年10月17日 
 */
public class BufferStreamDemo {

	/*
	 * 读入内存的字节缓存流写法
	 */
	private static void byteReader() {
		File file = new File("C:\\Users\\Desktop\\需要被删的\\新建文本文档 (4).txt");
		InputStream in;
		try {
			in = new FileInputStream(file);
			//构造一个字节缓冲流
			BufferedInputStream bis = new BufferedInputStream(in);
			byte[] bytes = new byte[2048];
			int len = -1;
			while((len=bis.read(bytes)) != -1) {
				System.out.println(new String(bytes,0,len));
		} 
			bis.close();
		}catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	/*
	 * 读入内存的字节缓存流,代码少一些,以及会自动关闭的写法
	 */
	private static void byteReader2() {
		File file = new File("C:\\Users\\Desktop\\需要被删的\\新建文本文档 (4).txt");
		try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))){
			byte[] bytes = new byte[2048];
			int len = -1;
			while((len=bis.read(bytes)) != -1) {
				System.out.println(new String(bytes,0,len));
		} 
		}catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	
	/*
	 * 写出文件的字节缓存流
	 */
	private static void byteWriter() {
		File file = new File("C:\\Users\\Desktop\\需要被删的\\新建文本文档 (4).txt");
		try {
			OutputStream out = new FileOutputStream(file);
			//构造一个字节缓冲流
			BufferedOutputStream bos = new BufferedOutputStream(out);
			
			//
			String info = "牛奶君";
			out.write(info.getBytes());
			
			bos.close();
			//out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		byteWriter();
		byteReader();
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值