字节流(拷贝图片)

package com.cn.input;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Author:Liu Zhiyong(QQ:1012421396)
* Version:Version_1
* Date:2016年7月25日16:30:21
* Desc:拷贝一张图片
*/
public class Demo4 {
	public static void main(String[] args){
		//建立数据的输入输出通道
		FileInputStream fileInputStream = null;
		//每新创建一个FileOutputStream的时候,默认情况下FileOutputStream的指针是指向了文件的开始位置。没写出一次,指针都会做出相应的移动
		FileOutputStream fileOutputStream = null;
		try {
			//找到目标文件
			File file = new File("f:/cool.png");
			File destFile = new File("g:/hh.png");
			fileInputStream = new FileInputStream(file);
			fileOutputStream = new FileOutputStream(destFile);
			//建立缓冲数据,边读边写
			byte[] buff = new byte[1024*300];
			int length = 0;
			while((length = fileInputStream.read(buff)) != -1){
//			fileOutputStream.write(buff); //这样拷贝不好,假如缓存很大,假如一次性读完了,则会造成拷贝好的图片变大。
				fileOutputStream.write(buff, 0, length);//读多少,写多少。
			}
		} catch (IOException e) {
			System.out.println("拷贝图片出错。。");
			throw new RuntimeException(e);
		}finally{
			try{
				if(fileOutputStream != null){
					//关闭资源原则:先开后关,后开后关
					fileOutputStream.close();
					System.out.println("关闭输出流资源成功");
				}
			}catch(IOException e){
				System.out.println("关闭输出流资源失败");
				throw new RuntimeException(e);
			}finally{
				if(fileInputStream !=  null){
					try {
						fileInputStream.close();
						System.out.println("关闭输入流资源成功");
					} catch (IOException e) {
						System.out.println("关闭输入流资源失败");
						throw new RuntimeException(e);
					}	
				}
			}
		}
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值