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

}

猜你喜欢

转载自blog.csdn.net/fingers_xwk/article/details/81022603
今日推荐