包装流和缓冲流

处理流/包装流(相对于节点流更高级)装饰设计模式/包装模式:

1:隐藏了底层的节点流的差异,并对外提供了更方便的输入/输出功能,让我们只关心高级流的操作.

2:使用处理流包装了节点流,程序直接操作处理流,让节点流与底层的设备做IO操作.

 

实际识别处理流/包装流非常简单,只要流的构造器参数不是一个物理节点,而是已经存在的流,那么这种流就一定是处理流,而所有节点流都是直接以物理IO节点作为构造器参数的。

 

使用处理流的优势:

1.使用处理流进行输入输出操作更简单

2.使用处理流的执行效率更高


----------------------------------------------------------

什么是缓冲流:

是一个包装流,目的起缓冲作用.包括:

BufferedInputStream:

BufferedOutputStream:

BufferedReader:

BufferedWriter:

 

int read():每次都从磁盘文件中读取一个字节.  直接操作磁盘文件性能极低.

解决方案:定义一个数组作为缓冲区.

byte[] buffer = new byte[1024]; 该数组其实就是一个缓冲区.

一次性从磁盘文件中读取1024个字节.  如此以来,操作磁盘文件的次数少了,性能得以提升.

提供的默认缓存区大小是8192(1024*8),我们一般不用修改大小.为了提供IO性能/效率,操作字节和字符流都习惯使用缓冲流给包装起来.


字节缓冲流:

//字节缓冲流
public class BufferStreamDemo {
	public static void main(String[] args) throws Exception {
		//字节缓冲输入流
		BufferedInputStream bin = new BufferedInputStream(new FileInputStream("text/hello.txt"));
		//IO操作
		byte[] buffer = new byte[1024];
		int len = -1;
		while((len = bin.read(buffer)) != -1){
			System.out.println(new String(buffer,0,len));
		}
		
		bin.close();
		
		//字节缓冲输出流
		BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream("text/hello.txt",true));
		//IO操作
		bout.write("Hhhh2333333".getBytes());
		bout.write("Hhhh2333333".getBytes());
		bout.close();
	}

}

字符缓冲流:

//字符缓冲流
public class BufferWriterReaderDemo {
	public static void main(String[] args) throws Exception {
		//字符缓冲输出流
		BufferedWriter out = new BufferedWriter(new FileWriter("text/hello",true));
		//IO操作
		out.write("白日依山尽");
		out.newLine();
		out.write("黄河入海流");
		out.close();
		
		//字符缓冲输入流
		BufferedReader in = new BufferedReader(new FileReader("text/hello.txt"));
		//IO操作
//		char[] buffer = new char[1024];
//		int len = -1;
//		while((len = in.read(buffer)) != -1){
//			System.out.println(new String(buffer,0,len));
//		}
		//String readLine() 
		String line = null;
		while((line = in.readLine()) != null){
			System.out.println(line);
		}
		in.close();
	
	}

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值