재귀적으로 파일/폴더를 복사/삭제하려면:

2995 단어 폴더
재귀적으로 파일/폴더를 복사/삭제하려면:
package cn.syswin.copy;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;

public class CopyFiles {

	private static AtomicLong delFileCount = new AtomicLong(0);
	private static AtomicLong copyFileCount = new AtomicLong(0);

	public static void main(String[] args) throws Exception {
		long start = System.currentTimeMillis();
		copyFiles("D:\\WorkSpace\\Test\\aa", "D:\\WorkSpace\\Test\\ee");
//		deleteFiles("D:\\WorkSpace\\Test\\ee");
		System.out.println(" ( ): " + ((System.currentTimeMillis() - start) / 1000 / 60));
	}

	//  
	public static void copyFiles(String originPath, String destPath) throws Exception {
		File file = new File(originPath);
		if (file.isDirectory()) {
			File f = new File(destPath);
			if (!f.exists()) {
				System.out.println(copyFileCount.incrementAndGet() + " " + f.toString());
				f.mkdir();
			}
			File[] files = file.listFiles();
			for (File file2 : files) {
				copyFiles(file2.toString(), destPath + File.separator + file2.getName());
			}
		} else {
			copy(originPath, destPath);
		}
	}

	//  
	public static void copy(String originPath, String destPath) throws IOException {
		File originFile = new File(originPath);
		File destFile = new File(destPath);
		if(!destFile.exists() || originFile.length() != destFile.length()) { //  
			System.out.println(copyFileCount.incrementAndGet() + " " + destPath + " [" +  originFile.length() + " " + destFile.length() + "]"); // + originPath + " >>> "
			DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(originFile)));
			byte[] data = new byte[in.available()];
			in.read(data);
			DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destFile)));
			out.write(data);
			out.flush();
			in.close();
			out.close();
		}
	}

	//  
	public static void deleteFiles(String path) {
		File f = new File(path);
		if (f.isDirectory()) {
			File[] file = f.listFiles();
			for (File file2 : file) {
				deleteFiles(file2.toString());
			}
		}
		deleteFile(f);
	}

	public static void deleteFile(File file) {
		if (file.exists()) {
			System.out.println(delFileCount.incrementAndGet() + " " + file.toString());
			file.delete();
		}
	}

}

좋은 웹페이지 즐겨찾기