java使用IO流实现文件夹的的复制

实现功能

源码

package cn.sxt.test2;
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 TestCopy {
	public static void main(String args[]) throws IOException {
		File srcDir = new File("D:\Test1");  //手动填写源文件夹路径
		File targetDir = new File("D:\Test2"); //手动填写目标路径
		copyDir(srcDir, targetDir); //调用复制文件夹方法
	}
//复制文件夹方法
	public static void copyDir(File srcDir, File targetDir) throws IOException {
		if (!targetDir.exists()) { //如果目标路径不存在
			targetDir.mkdir(); //则创建之
		}
		File[] files = srcDir.listFiles(); //列举目录下所有文件(包含子目录)存放至数组
		for (File file : files) {  //增强for循环提取文件
			if (file.isFile()) {  //判断是否为文件
				copyFile(new File(srcDir + "\" + file.getName()), new File(targetDir + "\" + file.getName())); //调用复制文件方法;创建新的File表示源文件名及目标文件名,文件名为源文件夹路径+文件名,目标文件名同理
			} else { //不是文件则为文件夹,以下为文件夹的处理方法
				copyDir(new File(srcDir + "\" + file.getName()), new File(targetDir + "\" + file.getName())); //如果当前file为文件夹,则再次调用copyDir方法(递归)
			}
		}
	}
	//复制文件方法
	public static void copyFile(File srcFile, File targetFile) throws IOException {
		// 提高读取效率,从数据源
		BufferedInputStream bis = null;
		// 提高写入效率,写到目的地
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(srcFile));
			bos = new BufferedOutputStream(new FileOutputStream(targetFile));
			// 边读边写
			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = bis.read(buf)) != -1) {
				bos.write(buf, 0, len);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// 关闭
			try {
				if (bos != null)
					bos.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if (bis != null)
					bis.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

运行展示

经验分享 程序员 微信小程序 职场和发展