JAvaでIOストリームを利用してフォルダとファイルをコピーする


JAvaのIOフローによるファイルとフォルダのコピー
package com.baojian.demo03;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 *         /*
 *   https://www.cnblogs.com/qingfengzhuimeng/p/6776445.html
*/
public class TestCopyFloderAndFile {

	public static void main(String[] args) throws IOException {
		//          ,              
		String sourcePath = "d:\\QQ";
		String destPath = "c:\\QQ";
		copyFile(sourcePath,destPath);
		System.out.println("**********       **********");
		
	}
	//         ,     
	private static void copyFile(String sourcePath,String destPath) throws IOException{
		//          File  
		File sourceFile = new File(sourcePath);
		//         
		if(!sourceFile.exists()){
			System.out.println("             !");
			return;
		}else if(sourceFile.isFile()){
			copyDocument(sourcePath,destPath);
			return;
		}
		//         File  
		File destFile = new File(destPath);
		//           ,        
		if(!destFile.exists()){
			destFile.mkdirs();
		}
		
		//                   
		File[] files = sourceFile.listFiles();
		//                      copyFile  ,             
		for(File file : files){
			System.out.println(file.getName());
			//       ,    copyFile  
			if(file.isDirectory()){
				copyFile(sourcePath + "\\" + file.getName(),destPath + "\\" + file.getName());
			}
			//      ,        
			if(file.isFile()){
				copyDocument(sourcePath + "\\" + file.getName(),destPath + "\\" + file.getName());
				System.out.println("    ");
			}
		}
	
	}
	//     
	public static void copyDocument(String sourcePath,String destPath) throws IOException {
		//          
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourcePath));
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath));
		//     
		byte[] buf = new byte[1024];
		int len = 0;
		while((len = bis.read(buf))!=-1){
			bos.write(buf, 0, len);
		}
		bos.close();
		bis.close();
	}
}