io流 拷贝

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

import org.junit.Test;

/*
 * 功能:复制文件
 * 技能:BufferedInputStream    BufferOutputStream   处理流
 * 
 * FileInputStream  FileOutputStream   节点流
 * 
 * 好处:提供了缓冲区 提高了读写效率
 * 
 * 原理:输入流和输出流两端都提供了默认大小8192的缓冲区内存空间,其实就是一个字节数组
 * 减少了读写硬盘的次数 提高了效率
 * 
 * 输出缓冲区的 刷新
 * 1.手动刷新    flush()
 * 2.自动刷新  缓冲区满了之后 会自动 flush()
 * 3.close()  关闭流的时候 会先调用flush()
 * 
 * 
 * 关闭高层流 的时候  会自动关闭底层流
 * */
public class TestCopy1 {
	public static void main(String[] args) throws IOException {
		InputStream is = new FileInputStream("d:\\a.txt");
		// 字节缓冲输入流 装饰模式
		BufferedInputStream bis = new BufferedInputStream(is);
		OutputStream os = new FileOutputStream("d:\\b.txt");
		BufferedOutputStream bos = new BufferedOutputStream(os);
		int n = bis.read();
		while (n != -1) {
			bos.write(n);
			bos.flush();
			n = bis.read();
		}
		// 底层调用了 缓冲流的 close 方法的时候 会 先调用 flush() 清空缓冲区 然后 关闭 节点流
		bos.close();
		// os.close();
		bis.close();
		// is.close();
	}

	@Test
	public void test1() {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream("d:\\a.txt"));
			bos = new BufferedOutputStream(new FileOutputStream("d:\\b.txt"));
			byte[] b = new byte[1024];
			int len = bis.read(b);
			while (len != -1) {
				bos.write(b);
				len = bis.read(b);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			bos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值