JAVA 好用的文件备份代码

  • Post author:
  • Post category:java


  • 好用的java文件备份工具

    这个工具是一边备份一边删除原来目录所有的要备份数据。

package cn.gitv.pro.charging.lncmcc.test;

import java.io.*;

/**
 * @author 
 * @create on  2019-12-05 10:10
 */
public class FileCopyUtils {


//    实现对目录的复制
//    在复制目录的过程中判断源文件下所有文件对象是否为目录,是的话则利用递归调用自己复制目录
//    如果是文件的话,则调用copyFile方法复制文件
    public static void copyDir(String srcPath,String destPath) {
        File src = new File(srcPath);//源头
        File dest = new File(destPath);//目的地
        //判断是否为目录,不存在则不作操作
        if(!src.isDirectory()) {
            return;
        }
        //判断目的地目录是否存在,不存在就创建目录
        if(!dest.exists()) {
            boolean mkdir = dest.mkdir();
        }
        //获取源头目录下的文件列表,每个对象代表一个目录或者文件
        File[] srcList = src.listFiles();
        if (null != srcList && srcList.length > 0){
            //遍历源头目录下的文件列表
            for (File aSrcList : srcList) {
                //如果是目录的话
                if (aSrcList.isDirectory()) {
                    //递归调用复制该目录
                    copyDir(srcPath + File.separator + aSrcList.getName(), destPath + File.separator + aSrcList.getName());
                    //如果是文件的话
                } else if (aSrcList.isFile()) {
                    //递归复制该文件
                    copyFile(srcPath + File.separator + aSrcList.getName(), destPath + File.separator + aSrcList.getName());
                }
                aSrcList.delete();
            }
        }
//        boolean delete = src.delete();
    }

//    实现对文件的复制
    public static void copyFile(String isFile, String osFile) {

        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(isFile);
            os = new FileOutputStream(osFile);
            byte[] data = new byte[1024];//缓存容器
            int len = -1;//接收长度
            while((len=is.read(data))!=-1) {
                os.write(data, 0, len);
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch(IOException e) {
            e.printStackTrace();
        }finally {
            //	释放资源 分别关闭 先打开的后关闭
            try {
                if(null!=os) {
                    os.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }
            try {
                if(null!=is) {
                    is.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }
        }
    }
    
    public static void main(String[] args) {
        copyDir("D:\\test3","D:\\test4");
    }
}



版权声明:本文为qq_25406669原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。