拷贝目录

package test;
import java.util.Date;
import java.io.*;

import java.util.*;

public class test {

	public static void main(String[] args) throws FileNotFoundException  {
	File f1=new File("C:\\Users\\Administrator\\Desktop\\gra_design\\code");
	File f2=new File("D:\\");
	copyDir(f2,f1);
	}
	private static void copyDir(File f2,File f1) {
		if (f1.isFile()) {
			FileInputStream in=null;FileOutputStream out=null;
			try {
				in =new FileInputStream(f1.getAbsoluteFile());
				out=new FileOutputStream((f2.getAbsolutePath().endsWith("\\")?f2.getAbsolutePath():f2.getAbsolutePath()+"\\")+f1.getAbsolutePath().substring(3));
				int readCount=0;
				byte[] b=new byte[1024*1024];
				while ((readCount=in.read(b))!=-1) {
					out.write(b,0,readCount);
				}
				out.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally {
				if (in!=null) {
					try {
						in.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				if (out!=null) {
					try {
						out.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				}
			}
			
			return;
			//检测到f1是一个文件,那么递归就结束了
		}
		File[] files=f1.listFiles();
		//获得目录下的全部文件
		for (File file:files) {
			if (file.isDirectory()) {
				String srcPath=file.getAbsolutePath();
				System.out.println(srcPath);
				String desPath=(f2.getAbsolutePath().endsWith("\\")?f2.getAbsolutePath():f2.getAbsolutePath()+"\\")+srcPath.substring(3);
				//先判断f2的路径最后有没有\\,没有的话就加。然后再跟去掉盘符的f1路径相加,组成最后的目标路径
				File newFile=new File(desPath);
				if (!newFile.exists()) {
					newFile.mkdir();
				}
				copyDir(newFile,file);
				//新建这个目录
			}
	
		}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值