/*
* 說明:
* 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);
}
}
}
}
}