package com.cn.buffered;
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;
/**
* Desc:
需求:使用缓冲输入输出数组字节流拷贝一张图片。
*/
public class Demo3 {
public static void main(String[] args) {
BufferedInputStream bufferedInputStream = null;
BufferedOutputStream bufferedOutputStream = null;
try{
//找到目标文件
File file = new File("f:/cool.png");
File descFile = new File("f:/cool2.png");
//建立数据输入输出通道
FileInputStream inputStream = new FileInputStream(file);
FileOutputStream fileOutputStream = new FileOutputStream(descFile);
//建立缓冲输入输出通道
bufferedInputStream = new BufferedInputStream(inputStream);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
//边读边写
int content = 0;
while((content = bufferedInputStream.read()) != -1){//read()方法返回值是读取到的内容
bufferedOutputStream.write(content);
// bufferedOutputStream.flush(); //这里加了flush()的话效率就会变低、但后面必须加close方法,把内存中的数据输出
}
}catch(IOException e){
System.out.println("打开资源文件出现异常。。。。");
throw new RuntimeException(e);
}finally{
try {
if(bufferedOutputStream != null){
bufferedOutputStream.close();
System.out.println("缓冲输出字节流关闭成功。。。。");
}
} catch (IOException e) {
System.out.println("缓冲输出字节流关闭失败。。。。");
throw new RuntimeException(e);
}finally{
try{
if(bufferedOutputStream != null){
bufferedInputStream.close();
System.out.println("缓冲输入字节流关闭成功。。。。");
}
}catch(IOException e){
System.out.println("缓冲输入字节流关闭失败。。。。");
throw new RuntimeException(e);
}
}
}
}
}