复制文件夹

 思路:先判断源目录sourceFolderPath存不存在,如果不存在则抛出异常结束程序的执行。如果存在,又因为目标目录可能不存在,所以先使用File类的mkdirs()创建目标目录targetFolderPath不然会抛出FileNotFoundException然后使用File类的listFiles()方法获取源目录sourceFolderPath下的所有文件或文件夹,判断,如果是文件则直接复制,如果是文件夹则递归。


 

package com.gk.io;

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

public class CopyMultilevelFolders {
	
	public static void main(String[] args) {
		
		String sourceFolderPath = "d:/123";		// 源目录,要求必须存在。
		String targetFolderPath = "d:/456";		// 目标目录
		
		if(!new File(sourceFolderPath).exists()) {
			throw new RuntimeException("源目录不存在...");
		}
		
		try {
			copy(sourceFolderPath, targetFolderPath);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 采用递归处理
	 * @param sourcePath
	 * @param targetPath
	 * @throws IOException
	 */
	private static void copy(String sourceFolderPath, String targetFolderPath) throws IOException {

		new File(targetFolderPath).mkdirs();		// 有可能目标目录不存在,所以先创建,不然会有FileNotFoundException异常
		
		File[] files = new File(sourceFolderPath).listFiles();	
		
		for (File sourceFile : files) {
			
			String sourceFileName = sourceFile.getAbsolutePath();	
			String targetFileName = targetFolderPath + "/" + sourceFile.getName();
			
			if(sourceFile.isFile()) {
				 copyFile(sourceFileName,targetFileName);          // 如果是文件则执行copyFile操作
				
			}else {
				copy(sourceFileName,targetFileName);		// 如果是文件夹则递归调用copy方法
			}
		}
	}

	/**
	 * 复制文件,使用BufferedStream组合,可以高效读取,
	 * 因为复制的文件有可能是二进制文件,所以不能使用字节流
	 * 
	 * @param sourceFileName:源文件路径
	 * @param targetFileName:目标文件路径
	 * @throws IOException
	 */
	private static void copyFile(String sourceFileName, String targetFileName) throws IOException {

		BufferedInputStream in = new BufferedInputStream(new FileInputStream(sourceFileName));
		BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(targetFileName));
		
		byte[] bys = new byte[1024];
		int len = 0;
		
		while((len = in.read(bys)) != -1) {
			
			out.write(bys, 0, len);
			out.flush();
		}
		
		// 释放资源
		in.close();
		out.close();
	}
	
}


运行前:





运行后在D盘生成了文件夹456:









猜你喜欢

转载自blog.csdn.net/leexichang/article/details/79292486