Java 文件夹拷贝

最近项目中需要拷贝某个目录及其下面的所有子文件,包括子文件夹。

思路:遍历某个目录下的所有文件,如果为文件,则直接拷贝;如果为文件夹,则递归遍历。


package com.xx.test.copy;

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

public class TestCopyDir {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		String sourceDirName = "D:/LuceneEx";
		String targetDirName = "D:/LuceneEx_backup";
		
		copyDir(sourceDirName,targetDirName);
		
	}

	/**
	 * 拷贝目录,递归的方法
	 * @param sourceDirName
	 * @param targetDirName
	 */
	public static void copyDir(String sourceDirName, String targetDirName) {
		
		File sourceDir = new File(sourceDirName);
		File targetDir = new File(targetDirName);
		
		if(sourceDir==null || !sourceDir.exists()){
			throw new RuntimeException("待拷贝的文件夹不存在..."+sourceDir.getAbsolutePath());
		}
		
		if(!sourceDir.isDirectory()){
			throw new RuntimeException("待拷贝的文件不是目录..."+sourceDir.getAbsolutePath());
		}
		
		if(!targetDir.exists()){
			targetDir.mkdirs();
		}
		
		File[] files = sourceDir.listFiles();
		
		for(int i=0;files!=null && i<files.length;i++){
			
			if(files[i].isFile()){	//复制文件
				
				copyFile(files[i],new File(targetDirName+File.separator+files[i].getName()));
				
			}else if(files[i].isDirectory()){	//复制目录,递归的方法
				
				// 复制目录   
				String dir1 = sourceDirName+File.separator+files[i].getName();  
				String dir2 = targetDirName+File.separator+files[i].getName();  
                copyDir(dir1, dir2);  
			}
			
		}
	}

	/**
	 * 拷贝单个的文件
	 * @param sourceFile	源文件
	 * @param targetFile	目标文件
	 */
	private static void copyFile(File sourceFile, File targetFile) {
		FileInputStream in = null;
		BufferedInputStream bis = null;
		FileOutputStream out = null;
		BufferedOutputStream bos = null;
		try {
			// 新建文件输入流并对它进行缓冲   
			in = new FileInputStream(sourceFile);  
			bis = new BufferedInputStream(in);  
  
			// 新建文件输出流并对它进行缓冲   
			out = new FileOutputStream(targetFile);  
			bos = new BufferedOutputStream(out);  
			  
			// 缓冲数组   
			byte[] b = new byte[1024 * 5];  
			int len;  
			while ((len =bis.read(b)) != -1) {  
			    bos.write(b, 0, len);  
			}  
			// 刷新此缓冲的输出流   
			bos.flush();  
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(bos!=null)
					bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			try {
				if(bis!=null)
					bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}






  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值