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();
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章