/*
* 說明:
* 1.設(shè)計思想:想讀取文件当纱,然后立即寫入;
* 2.關(guān)閉原則:先開的后關(guān),后開的先關(guān);
*/
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(); //調(diào)用拷貝函數(shù)
}
//照片拷貝函數(shù)
public static void copyImage(){
//1.定位源文件和目標(biāo)文件的位置
File srcFile = new File("C:\\DSC_0303.jpg");
File desFile = new File("G:\\lin.jpg");
//2.構(gòu)建文件輸入和輸出通道
FileInputStream srcInput = null;
FileOutputStream desOutput = null;
int length = 0;
byte[] buf = new byte[2024];//緩沖數(shù)組
//捕獲異常
try{
srcInput = new FileInputStream(srcFile);
desOutput = new FileOutputStream(desFile);
//3.讀取數(shù)據(jù)到內(nèi)存蹂安,并從內(nèi)存寫數(shù)據(jù)到硬盤(內(nèi)存是中轉(zhuǎn)站)
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("寫入資源關(guān)閉成功");
}
}catch(IOException e){
System.out.println("關(guān)閉文件失敗");
throw new RuntimeException(e);
}finally{
try{
if(srcInput != null){
srcInput.close();
System.out.println("讀入資源關(guān)閉成功");
}
}catch(IOException e){
System.out.println("讀入資源關(guān)閉失敗!");
throw new RuntimeException(e);
}
}
}
}
}