天天看點

利用位元組輸入和輸出流實作簡單檔案複制

利用位元組輸入和輸出流實作簡單檔案複制

package cn.sxt.java54;

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

public class TestRemoveCopay {
/**
 * 利用檔案位元組流實作簡單檔案複制
 * @param args
 */
	public static void main(String[] args) {
	  //建立橋梁
		FileInputStream fi=null;
		//檔案輸出流,複制到的檔案
		FileOutputStream fo=null;
		try {
			fi = new FileInputStream(new File("D:\\test.txt"));
			fo = new  FileOutputStream("D:\\B.txt");
			//建立數組,中轉站。
			byte[] by=new byte[1024];
			//接收檔案
			int len=0;
			while((len=fi.read(by))!=-1) {
			      // fo.write(len);	
				fo.write(by, 0, len);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			
			//關閉資源
			try {
				if(fi!=null) {
				fi.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(fo!=null) {//判斷一下,以防空指針異常
				fo.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}