需求: 拷貝一張圖檔。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyImage {
public static void main(String[] args) throws IOException {
//找到目标檔案
File inFile = new File("F:\\美女\\1.jpg");
File destFile = new File("E:\\1.jpg");
//建立資料的輸入輸出通道
FileInputStream fileInputStream = new FileInputStream(inFile);
FileOutputStream fileOutputStream = new FileOutputStream(destFile); //追加資料....
//每新建立一個FileOutputStream的時候,預設情況下FileOutputStream 的指針是指向了檔案的開始的位置。 每寫出一次,指向都會出現相應移動。
//建立緩沖資料,邊讀邊寫
byte[] buf = new byte[1024];
int length = 0 ;
while((length = fileInputStream.read(buf))!=-1){ //最後一次隻剩下了824個位元組
fileOutputStream.write(buf,0,length); //寫出很多次資料,是以就必須要追加。
}
//關閉資源 原則: 先開後關,後開先關。
fileOutputStream.close();
fileInputStream.close();
}
}
帶異常處理的方式
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.management.RuntimeErrorException;
/*
IO異常 的處理
*/
public class Demo1 {
public static void main(String[] args) {
// readTest();
copyImage();
}
// 拷貝圖檔
public static void copyImage() {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
// 找到目标檔案
File inFile = new File("F:\\美女\\1.jpg");
File outFile = new File("E:\\1.jpg");
// 建立輸入輸出通道
fileInputStream = new FileInputStream(inFile);
fileOutputStream = new FileOutputStream(outFile);
// 建立緩沖數組,邊讀邊寫
byte[] buf = new byte[1024];
int length = 0;
while ((length = fileInputStream.read(buf)) != -1) {
fileOutputStream.write(buf, 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);
}
}
}
}
}
public static void readTest() {
FileInputStream fileInputStream = null;
try {
// 找到目标檔案
File file = new File("F:\\aaaaa.txt");
// 建立資料輸入通道
fileInputStream = new FileInputStream(file);
// 建立緩沖數組讀取資料
byte[] buf = new byte[1024];
int length = 0;
while ((length = fileInputStream.read(buf)) != -1) {
System.out.print(new String(buf, 0, length));
}
} catch (IOException e) {
/*
* //處理的代碼... 首先你要阻止後面的代碼執行,而且要需要通知調用者這裡出錯了... throw new
* RuntimeException(e);
* //把IOException傳遞給RuntimeException包裝一層,然後再抛出,這樣子做的目的是
* 為了讓調用者使用變得更加靈活。
*/
System.out.println("讀取檔案資源出錯....");
throw new RuntimeException(e);
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
System.out.println("關閉資源成功...");
}
} catch (IOException e) {
System.out.println("關閉資源失敗...");
throw new RuntimeException(e);
}
}
}
}