/*
* 说明:
* 1.设计思想:想读取文件,然后立即写入;
* 2.关闭原则:先开的后关,后开的先关;
*/
package com.michael.iodetail;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/*
*
*/
public class Demo3 {
public static void main(String[] args){
copyPhoto(); //调用拷贝函数
}
//照片拷贝函数
public static void copyImage(){
//1.定位源文件和目标文件的位置
File srcFile = new File("C:\\DSC_0303.jpg");
File desFile = new File("G:\\lin.jpg");
//2.构建文件输入和输出通道
FileInputStream srcInput = null;
FileOutputStream desOutput = null;
int length = 0;
byte[] buf = new byte[2024];//缓冲数组
//捕获异常
try{
srcInput = new FileInputStream(srcFile);
desOutput = new FileOutputStream(desFile);
//3.读取数据到内存,并从内存写数据到硬盘(内存是中转站)
while((length = srcInput.read(buf))!=-1){
desOutput.write(buf,0,buf.length);
}
}catch(IOException e){
System.out.println("拷贝文件出错...");
throw new RuntimeException(e);
}finally{
try{
if(desOutput != null){
desOutput.close();
System.out.println("写入资源关闭成功");
}
}catch(IOException e){
System.out.println("关闭文件失败");
throw new RuntimeException(e);
}finally{
try{
if(srcInput != null){
srcInput.close();
System.out.println("读入资源关闭成功");
}
}catch(IOException e){
System.out.println("读入资源关闭失败!");
throw new RuntimeException(e);
}
}
}
}
}