폴더 복사 반복

16612 단어 학습 기록
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 *  copy
 */
public class Test3 {
     
	public static void main(String[] args){
     
		File file = new File("F:\\1");
		File file2 = new File("F:\\2");
		if (file.getAbsolutePath().equals(file2.getAbsolutePath())) {
     
			System.out.println(" copy( : )");
			return;
		}
		//  
		if (!file.exists()) {
     
			System.out.println(" ");
			return;
		}
		// file , copy
		if (file.isFile()) {
     
			// file copy ,copy 
			System.out.println(" copy , ");
			copyFile(file, file2);
			System.out.println(" copy ");
			return;
		}
		// file 
		if (file.isDirectory()) {
     
			System.out.println(" copy , ");
			copyAllFiles(file,file2);
			System.out.println(" copy ");
		}else {
     
			System.out.println(" , copy ");
		}
	}
	public static void copyAllFiles(File file,File file2) {
     
		File[] listFiles = file.listFiles();
		if (listFiles!=null) {
     
			for (File f : listFiles) {
     
				File temp = new File(file2.getAbsoluteFile(),f.getName());
				if (f.isDirectory()) {
     
					temp.mkdirs();
					copyAllFiles(f,temp);
				}else {
     
					copyFile(f, temp);
				}
			}
		}
	}
	public static void copyFile(File f1,File f2){
     
		FileInputStream fileInputStream = null;
		FileOutputStream fileOutputStream = null;
		try {
     
			fileInputStream = new FileInputStream(f1);
			fileOutputStream = new FileOutputStream(f2);
			int length = 0;
			byte[] bytes = new byte[1024];
			while ((length=fileInputStream.read(bytes))!=-1) {
     
				fileOutputStream.write(bytes,0,length);
				//System.out.println(" ");
			}
		} catch (FileNotFoundException e) {
     
			e.printStackTrace();
		} catch (IOException e) {
     
			e.printStackTrace();
		}finally {
     
			try {
     
				if (fileInputStream!=null) {
     
					fileInputStream.close();
				}
			} catch (IOException e) {
     
				e.printStackTrace();
			}
			try {
     
				if (fileOutputStream!=null) {
     
					fileOutputStream.close();
				}
			} catch (IOException e) {
     
				e.printStackTrace();
			}
		}
	}
}

좋은 웹페이지 즐겨찾기