java学习笔记之IO编程—目录和文件的拷贝

     进行文件或目录的拷贝时,要先判断处理对象是文件还是目录,如果是文件则直接拷贝,如果是目录还需要拷贝它的子目录及其文件,这就需要递归处理了

import java.io.*;

class FileUtil{
    private File srcFile;
    private File desFile;
    public FileUtil(String src, String des) {
        this(new File(src),new File(des));
    }
    public FileUtil(File srcFile, File desFile) {
        this.srcFile = srcFile;
        this.desFile = desFile;
    }
    public boolean copy() throws Exception {
        if(!srcFile.exists()) {
            System.out.println("源文件不存在,文件拷贝失败");
            return false;
        }
        return this.copyFileImpl(srcFile, desFile);//进行文件拷贝
    }
    public boolean copyDir() throws Exception {
        this.copyImpl(this.srcFile);//对目录用递归处理
        return true;
    }
    public void copyImpl(File file) throws Exception {//递归
        if(file.isDirectory()) {//处理对象是目录,进行递归处理
            File[] results = file.listFiles();
            if(results != null) {
                for(int i=0;i<results.length;i++) {
                    copyImpl(results[i]);
                }
            }
        }else {//处理对象是文件,进行拷贝处理
            String newFilePath = file.getPath().replace(this.srcFile.getPath()+File.separator, "");
            File newFile = new File(this.desFile,newFilePath);//拷贝的目标路径
            this.copyFileImpl(file, newFile);
        }
    }
    public boolean copyFileImpl(File srcFile,File desFile) throws Exception {
        if(!desFile.getParentFile().exists()) {
            desFile.getParentFile().mkdirs();//创建父目录
        }
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(srcFile);
            output = new FileOutputStream(desFile);
            byte[] data = new byte[1024];
            int len = 0;
            while((len = input.read(data)) != -1) {
                output.write(data,0,len);
            }
            return true;
        }catch(Exception e) {
            throw e;
        }finally {
            if(input != null)
                input.close();
            if(output != null)
                output.close();
        }
    }
}
public class FileCopyDemo {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        String src = "D:"+File.separator+"NBA";//源路径
        String des = "D:"+File.separator+"NBA2";//目标路径
        FileUtil fu = new FileUtil(src,des);
        if(new File(src).isFile()) {
            System.out.println("文件拷贝:"+fu.copy());//处理对象是文件,调用copy()方法
        }else {
            System.out.println("目录拷贝:"+fu.copyDir());//处理对象是目录,调用copyDir()方法
        }
    }

}
posted @ 2020-01-18 21:19  幼儿猿班长  阅读(138)  评论(0编辑  收藏  举报