使用字节流实现图片的拷贝

* 使用字节流实现图片的拷贝*

1:使用FileInputStream与FileOutputStream完成操作
2:使用BufferedInputStream与BufferedOutputStream完成操作
3:使用FileInputStream与FileOutputStream,并定义中间临时缓冲区

法一:使用FileInputStream与FileOutputStream完成操作

public static void copy1(String name) throws IOException {
//定义字节读取流对象
FileInputStream fis = new FileInputStream(name); //定义字节输出流对象
 FileOutputStream fos = new FileOutputStream("copy1.jpg");
//定义int变量,用于接受read方法返回的字节数据
int tem = -1;
while((tem = fis.read()) != -1) {
//通过输出流对象的写方法,在新的文件中写入数据 fos.write(tem);
//tem = fis.read();
 }
//关流
fis.close();
fos.close();
}

法二:
使用BufferedInputStream与BufferedOutputStream完成操作

public static void copy2(String name) throws IOException {
FileInputStream fis = new FileInputStream(name); FileOutputStream fos = new FileOutputStream("copy2.jpg");
//定义缓冲读取流对象
BufferedInputStream bfis = new BufferedInputStream(fis);
//定义缓冲输出流对象
BufferedOutputStream bfos = new BufferedOutputStream(fos);
int tem = -1;
//这个read跟上一个方法重的read是有区别的,上一个read是读一个数据写一个数据,效率较差,此read是先把一堆数据读入缓冲区,再统一写数据,效率较高
while((tem = bfis.read()) != -1) {
bfos.write(tem);
}
//关流
bfis.close();
bfos.close();
}

方法3:使用FileInputStream与FileOutputStream,并定义中间临时缓冲区

public static void copy3(String name) throws IOException {
FileInputStream fis = new FileInputStream(name); FileOutputStream fos = new FileOutputStream("copy3.jpg");
//此方法运用了第二种方法的原理,自己定义了一个缓冲区,用于缓冲数据,从而提高效率
byte[] by = new byte[1024];
//定义变量,用于记录读入的数据的长度
int len=-1;
while((len = fis.read(by)) != -1) {
//写入有效数据
fos.write(by, 0, len);
}
//关流
fis.close();
fos.close();
}

转自:http://blog.sina.com.cn/s/blog_715d1a940101ruef.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值