前一段时间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); } }}