1. 程式人生 > >【Java筆記】IO流中檔案複製及異常處理

【Java筆記】IO流中檔案複製及異常處理

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
	public static void main(String[] args) throws IOException {
		// 建立位元組流的引用變數
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			// 繫結資料來源和目標檔案
			fis = new FileInputStream("d:\\a.txt");
			fos = new FileOutputStream("d:\\b.txt");
			byte[] bytes = new byte[1024];
			int len = 0;
			while ((len = fis.read(bytes)) != -1) {// 讀取資料來源位元組
				fos.write(bytes, 0, len);// 寫入位元組到目標檔案
			}
		} catch (IOException ex) {
			System.out.println(ex);
			throw new RuntimeException("檔案複製失敗");
		} finally {
			try {
				fis.close();
			} catch (Exception ex) {
				throw new RuntimeException("關閉輸入流失敗!");
			} finally {
				try {
					fos.close();
				} catch (Exception ex) {
					throw new RuntimeException("關閉輸出流失敗!");
				}
			}
		}
	}
}