IO操作(3):装饰流(字节缓冲流BufferedInput/OutputStream)

筅森魡賤 提交于 2020-01-18 13:50:22

装饰流

IO流按功能可分为节点流和处理流(装饰流),装饰流是在节点流基础上进行操作可以提高IO流的性能。
如果不需要装饰流则需要对硬盘重复操作,性能不高,BufferedInputStream可以相当于设置一个缓冲区先将要读取的内容放在一辆车上统一进行存取(默认内容为8k)
(FilterInputStream为装饰流)
结构

代码举例

BufferedInputStream

public class DecorateBufferInput {
	public static void main(String[] args) throws IOException {
		//1、创建源
		File src = new File("abc.txt");
		//2、选择流
		InputStream is = null;
		BufferedInputStream bis = null;
		try {
			is  = new FileInputStream(src);
			bis = new BufferedInputStream(is);            //设置缓冲数组默认为8K
			//上面的可以直接改写为下面一行
			//is = new BufferedInputStream(new FileInputStream(src));
			//3、操作分段读取
			byte[] flush = new byte[1024];
			int len = -1;
			while((len=is.read())!=-1)
			{
				String str = new String(flush,0,len);
				System.out.println(str);
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}finally {
			if(null!=is)
			{
				is.close();
			}
			if(null!=bis)
			{
				bis.close();
			}
		}
	}
}

BufferedOutputStream

public class DecorateBufferedOutput {
	public static void main(String[] args) {
		File dest = new File("dest.txt");
		OutputStream os = null;
		try {
			os = new BufferedOutputStream(new FileOutputStream(dest));
			String msg = "ilovewangjiyu";
			byte[] datas = msg.getBytes();
			os.write(datas,0,datas.length);
			os.flush();
		}catch(IOException e)
		{
			e.printStackTrace();
		}finally {
			if(null!=os)
			{
				try {
					os.close();
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
		}
	}
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!