【小程序】利用java I/O流技術實現一個照片拷貝功能

/*

* 說明:

* 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);

}

}

}

}

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容