java实现文件拷贝

package java_07_12;

/**
 * 文件拷贝实例
 * 文件内容:目录,文件
 * 目录处理:递归,记录路径:isDirectory()
 * 文件:拷贝,字节流,可能有非纯文本
 * 父目录文件不能拷入子目录
 * 目录与文件不能同名
 * 获取文件名:getName()
 * 队列File[]储存当前目录下所有文件及目录:listFiles()
 * @author xiao
 * @for training
 */

import java.io.*;

public class FileCopyDemo {
	
	String path;//当前目录的路径
	String destination;//目标目录路径
	File root;//待拷贝文件
	File desFile;//目标文件
	File[] files;//当前目录中的所有目录及普通文件
	
	FileCopyDemo(String path,String destination){
		this.path  = path;
		this.destination = destination;
	}
	
	public void copy() {
		
		root = new File(path);
		files = root.listFiles();//当前目录所有子目录及普通文件
		destination = destination + "\\" + root.getName();//待拷贝文件的新路径
		desFile = new File(destination);
		if(!desFile.mkdirs()){//创建目录
			System.out.println("目录拷贝失败");
			return;
		}
		
		if(files.length == 0) {
			return;//空目录
		}
		
		
		for(int i=0 ; i<files.length ; i++) {
			if(files[i].isDirectory()) {//目录
				new FileCopyDemo(files[i].getAbsolutePath(),destination).copy();//递归
			}else {//普通文件
				copyCommonFile(files[i]);
			}
		}
	}
	
	public void copyCommonFile(File file) {//拷贝普通文件
		
		String commonPath = destination + "\\" + file.getName();//普通文件的新路径
		File newFile = new File(commonPath);
		try {
			
			BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));//输入流
			BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(newFile));//输出流
			
			byte[] b = new byte[1024];//缓冲
			int len = 0;//一次读取长度
			while((len = in.read(b)) != -1) {
				out.write(b);
			}
			out.flush();//刷新缓冲区
			
			out.close();//关闭流
			in.close();
			
		} catch (FileNotFoundException e) {
			// TODO 自动生成的 catch 块
			System.out.println("文件流创建失败");
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			System.out.println("文件读取失败");
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		String path= "C:\\Users\\Administrator\\Desktop\\图片\\java操作";
		String destination = "C:\\Users\\Administrator\\Desktop\\图片\\储存";
		FileCopyDemo demo = new FileCopyDemo(path, destination);
		demo.copy();
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值