黑马程序员——IO基础——练习:按原文件的目录层次复制所有文件到目标文件夹

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

/**
 * 实现功能:将文件或文件夹,按照原有目录层次复制到目标文件夹(windows复制粘贴)
 * 
 */
package jiangliang;

import java.util.*;

import java.io.*;

class CopyAllFiles{
	
	public static void main(String[] args) throws Exception{
		
		copy("c:\\aaa","d:\\");//测试
	}
	/**
	 * 将getFiles() 和 copyFromArray() 组合,并且复制的可以是文件或文件夹
	 * @param srcPath
	 * @param tarPath
	 * @throws IOException
	 */
	public static void copy(String srcPath,String tarPath) throws IOException{
		
		File srcFile = new File(srcPath);
		ArrayList<String> ar = new ArrayList<>();
		
		if(srcFile.isFile()){
			ar.add(srcPath);
			copyFromArray(ar,tarPath);
		}
		else {
			getFiles(new File(srcPath),ar);
			copyFromArray(ar,tarPath);		
		}
			
	}
	/**
	 * 遍历一个存放文件路径的ArrayList集合,逐个复制套目标文件夹
	 * @param ar:存放文件路径的ArrayList集合
	 * @param toPath:目标文件夹路径
	 * @throws IOException
	 */
	public static void copyFromArray(ArrayList<String> ar,String toPath) throws IOException{
		//replaced:获取要复制文件的父文件夹路径,这个父路径字符串替换成目标文件夹路径,就是集合中每个
		//			文件和文件夹路径将要复制到的目标路径
		String replaced = new File(ar.get(0)).getParent();
		
		for(String s:ar){
			File file = new File(s);	
			File toFile = new File(s.replace(replaced, toPath));//根据源文件路径,计算 目标文件路径

			if(file.isDirectory())				
				toFile.mkdirs();			
			else{
				BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
				BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(toFile));
				byte[] b = new byte[1024];
				int len = 0;
				while((len = bis.read(b))!=-1){
					bos.write(b,0,len);
					bos.flush();
				}
				bis.close();
				bos.close();
			}
				
		}
		
	}
	/**
	 * 遍历文件夹,返回所有子文件及文件夹路径
	 * @param file:要拷贝的文件夹(必须是文件夹)
	 * @param ar:返回的ArrayList<String>
	 */
	public static void getFiles(File file,ArrayList<String> ar){
		File[] files = file.listFiles();
		ar.add(file.getAbsolutePath());
		for(File f:files){
			if(f.isDirectory())
				getFiles(f,ar);
			else
				ar.add(f.getAbsolutePath());
		}
		
	}
	
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值