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);
}
}
}
}
}
}
字节流(拷贝图片)
最新推荐文章于 2022-07-25 23:38:29 发布