java 文件夹合并

      前一段时间android项目中用到文件夹合并,百度一下尽然没有合适的,自己写了一个递归处理的,还可以简化,但是稳定运行了,也就没有继续修改了。


public classFileTools {

private String mSourcePath;
private String mDesPath;
private boolean mResult;

private void FileTools() {
}

static class Instance {
    private static FileTools fileTools = new FileTools();
}

public static FileTools getInstance() {
    return Instance.fileTools;

}
/**
 * 用于同级合并两个文件夹
 *
 * @param sourceFolderPath 源文件的绝对路径  /data/com.dazhihui/temp
 * @param desFolderPath    目的文件的 /data/com.dazhihui/web
 * @return
 */
public boolean mergeFolder(String sourceFolderPath, String desFolderPath) {
    if (TextUtils.isEmpty(sourceFolderPath)) {
        return true;
    }
    if (TextUtils.isEmpty(desFolderPath)) {
        return false;
    }
    this.mSourcePath = sourceFolderPath;
    this.mDesPath = desFolderPath;
    File sourceFile = new File(mSourcePath);
    mResult = true;
    try {
        File[] fileList = sourceFile.listFiles();
        for (File file :
                fileList) {
            merge(file);
        }
    } catch (Exception e) {
        return false;
    }
    return mResult;

}

private void merge(File sourceFile) {
    //先找源文件相当于初始路劲的相对路径 才能找到目的文件的路径
    String sourcePath = sourceFile.getAbsolutePath();
    String relativePath = sourcePath.substring(mSourcePath.length() + 1);
    String desPath = mDesPath + File.separator + relativePath;
    File findDesFile = new File(desPath);
    if (sourceFile.isDirectory()) {
        //目录合并  即判断目的文件里面有没有该目录 有则不动 没有则创建
        if (findDesFile.exists()) {
        } else {
            findDesFile.mkdirs();
        }
        File[] fileList = sourceFile.listFiles();
        for (File file :
                fileList) {
            merge(file);
        }
    } else {
        //源文件为文件 则替换
        if (findDesFile.exists()) {
            findDesFile.delete();
        }
        sourceFile.renameTo(findDesFile);
    }
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值