1. 程式人生 > >1.實現目錄的拷貝(遞迴)---暫時我還不會!!

1.實現目錄的拷貝(遞迴)---暫時我還不會!!

今天學的,作業寫不出來??難受!!

package cn.ketang.zuoye01;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyDemo {

	public static void main(String[] args) {
		String srcPath = "E:\\feiq\\大資料-java基礎\\第八天";
		File src = new File(srcPath);
		String desPath = "D:\\tmp";
		File des = new File(desPath);
		copyDir(src, des);
	}

	public static void copyDir(File src, File des) {
		if (src.isDirectory()) {
			File temp = new File(des, src.getName());
			temp.mkdirs();
			for (File file : src.listFiles()) {
				copyDir(file, temp);
			}

		} else {
			copyFile(src, new File(des, src.getName()));
		}
	}

	public static void copyFile(File src, File des) {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(src);
			out = new FileOutputStream(des);
			byte[] b = new byte[1024];
			int len = 0;
			while ((len = in.read(b)) != -1) {
				out.write(b, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}