java遍历文件夹支付至文件到指定目录

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

public class CopyFolder {

	private  long total = 0l;
	
	public static void main(String[] args) {

		try {
			//源目录
			String srcStr = "d:\\im";
			//目标目录
			String destStr = "d:\\ims";
			File src = new File(srcStr);
			File des = new File(destStr);
			new CopyFolder().copyFolder(src, des);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void copyFolder(File srcFolder,File destFolder) throws Exception
	{
		File[] files = srcFolder.listFiles();
		for (File file : files)
		{
			if(file.isFile())
			{
				String pathname = destFolder+File.separator+file.getName();
		    	 File dest = new File(pathname);
		    	 File destPar =  dest.getParentFile();
		    	 destPar.mkdirs();
		    	 if(!dest.exists())
		    	 {
		    		 dest.createNewFile();
		    	 }
		    	 copyFile(file, dest);
			}else{
				 copyFolder(file, destFolder);
			}
		}
	}
	/***
	 * copy file
	 * 
	 * @param src 源目录
	 * @param dest 目标目录
	 */
	private void copyFile(File src, File dest) throws Exception {
		BufferedInputStream reader = null;
		BufferedOutputStream writer = null;
		try {
			reader = new BufferedInputStream(new FileInputStream(src));
			writer = new BufferedOutputStream(new FileOutputStream(dest));
			byte[] buff = new byte[reader.available()];
			while ((reader.read(buff)) != -1) {
				writer.write(buff);
			}
			total++;
			String temp = "\ncopy:\n"+src+"\tsize:"+src.length()+"\nto:\n"+dest+"\tsize:"+dest.length()+"\n complate\n totoal:"+total;
			System.out.println(temp);
		} catch (Exception e) {
			throw e;
		} finally {
			writer.flush();
			writer.close();
			reader.close();
			
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值