Java_143_IO_缓冲流_BufferedInputStream_默认8K_BufferedOutputStream

本文详细介绍了Java中用于提高I/O性能的缓冲流BufferedInputStream和BufferedOutputStream,讲解了它们如何通过内部默认8KB缓冲区提升读写效率,并提供了使用示例,包括如何创建及如何与FileInputStream和FileOutputStream结合使用。

InputStream in = new BufferedInputStream(new FileInputStream(src))

OutputStream out = new BufferedOutputStream(new FileOutputStream(src))

package IOStudy;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


/**
 * 处理流:装饰流
 * 
 * 字节缓冲流:提高读写性能
 * BufferedInputStream
 * BufferedOutputStream
 * 
 * 1.缓冲流提升性能
 * 2.任何处理流底层都是节点流
 * 3.流只需要释放最外层的处理流(装饰流),处理流会自动释放内部的节点流,如果想手动释放流需要从里到外依次释放
 * 
 * BufferedInputStream(InputStream in,int size) 创建指定缓冲区大小的BufferedInputStream,并保存其参数,输入流in供以后使用.
 * 默认8K,可以自己指定
 * 
 * 
 * 四个步骤: 分段读取,加入缓冲流
 * 1.创建源
 * 2.选择流
 * 3.操作
 * 4.释放资源
 * @author pmc
 *
 */
public class chuliliuIO3 {
	public static void main(String[] args) {
		long t1=System.currentTimeMillis();
		xFile();
		long t2=System.currentTimeMillis();
		dFile();
		System.out.println(t2-t1);
	}
	//分段读取
	private static void dFile(){
		//创建源
		File src=new File("txt.txt");
		//选择流
		InputStream in=null;
		try{
			in=new BufferedInputStream(new FileInputStream(src));
			byte[] temp=new byte[10];
			int len=0;
			while((len=in.read(temp))!=-1){
				System.out.print(new String(temp,0,len));
			}
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			if(in!=null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	//分段写入
	private static void xFile(){
		//1.创建源
		File src=new File("txt.txt");
		//2.选择流
		OutputStream out=null;
		try{
			out=new BufferedOutputStream(new FileOutputStream(src,true));
			String msg="my code\n";
			out.write(msg.getBytes());
			out.flush();
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	//自动释放资源try()...
	private static void xsFile(){
		//1.创建源
		File src=new File("txt.txt");
		//2.选择流
		
		try(OutputStream out=new BufferedOutputStream(new FileOutputStream(src,true))){
			String msg="my code\n";
			out.write(msg.getBytes());
			out.flush();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr_Pmc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值