java中利用IO流复制文件夹和文件

java中的IO流实现文件和文件夹的复制
package com.baojian.demo03;

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;

/*
 * 复制文件夹和文件/*
 * 参考https://www.cnblogs.com/qingfengzhuimeng/p/6776445.html
*/
public class TestCopyFloderAndFile {

	public static void main(String[] args) throws IOException {
		// 调用复制文件的方法, 传递文件源和文件复制的目的
		String sourcePath = "d:\\QQ";
		String destPath = "c:\\QQ";
		copyFile(sourcePath,destPath);
		System.out.println("**********文件夹复制完成**********");
		
	}
	// 复制文件夹的方法,利用了回调
	private static void copyFile(String sourcePath,String destPath) throws IOException{
		// 利用源文件路径创建File对象
		File sourceFile = new File(sourcePath);
		// 判断路径是否合法
		if(!sourceFile.exists()){
			System.out.println("您输入的文件源不是合法路径!");
			return;
		}else if(sourceFile.isFile()){
			copyDocument(sourcePath,destPath);
			return;
		}
		// 利用目的路径创建File对象
		File destFile = new File(destPath);
		// 判断目的路径是否存在,如果不存在则创建
		if(!destFile.exists()){
			destFile.mkdirs();
		}
		
		// 获取目的源下面的所有文件和文件夹列表
		File[] files = sourceFile.listFiles();
		// 遍历源文件下的文件类型如果是文件夹继续调用copyFile方法,如果是文件调用文件复制方法
		for(File file : files){
			System.out.println(file.getName());
			// 如果是文件夹,继续调用copyFile方法
			if(file.isDirectory()){
				copyFile(sourcePath + "\\" + file.getName(),destPath + "\\" + file.getName());
			}
			// 如果是文件,则调用文件的方法
			if(file.isFile()){
				copyDocument(sourcePath + "\\" + file.getName(),destPath + "\\" + file.getName());
				System.out.println("复制完成");
			}
		}
	
	}
	// 复制文件
	public static void copyDocument(String sourcePath,String destPath) throws IOException {
		// 创建字节缓冲流对象
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourcePath));
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath));
		// 复制文件
		byte[] buf = new byte[1024];
		int len = 0;
		while((len = bis.read(buf))!=-1){
			bos.write(buf, 0, len);
		}
		bos.close();
		bis.close();
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值