Java文件夹的复制

Java_文件夹的复制

1.复制一个文件
2.指定目录下的一个文件
3.指定目录下的所有文件及子目录下的所有文件

import java.io.*;

public class TestCopyFile {
	public static void main(String[] args) {
		File srcFile = new File("D:\\a.txt");
		File targetFile = new File("D:\\b.txt");
		//调用复制文件的方法
		copyFile(srcFile,targetFile);
		
		//复制整个文件夹
		File srcDir = new File("D\\abc");
		File targetDir = new File("E:\\abc");
		copyDir(srcDir,targetDir);
	}
	
	public static void copyDir(File srcDir,File targetDir) {//复制整个文件夹
		if(!targetDir.exists()) {
			targetDir.mkdir();//如果目录不存在,使用File类的方法进行创建目录
		}
		File[] files = srcDir.listFiles();  //获取指定目录下的所有file
		for(File file:files) {
			if(file.isFile()) {//是一个文件
				copyFile(new File(srcDir+"\\"+file.getName()),new File(targetDir+"\\"+file.getName()));
				
			}else {
				//如果是目录
				copyDir(new File(srcDir+"\\"+file.getName()),new File(targetDir+"\\"+file.getName()));
			}
		}
				
	}
	
	public static void copyFile(File srcFile,File targetFile) {  //复制指定文件
		//(1)提高读取效率,从数据源
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			FileInputStream fis = new FileInputStream(srcFile);
			bis = new BufferedInputStream(fis);
			//(2)提高写入效率,写到目的地
			FileOutputStream fos = new FileOutputStream(targetFile);
			bos = new BufferedOutputStream(fos);
			//(3)边写边读
			byte[] buf = new byte[1024]; //中转站
			int len = 0; //存储读到的字符数
			while((len=bis.read(buf))!=-1){
				bos.write(buf, 0, len);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			//(4)关闭
			if(bos!=null) {
				try {
					bos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(bis!=null) {
				try {
					bis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}
		
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值