Move directory to another location - Android java.io

Android examples for java.io:Directory

Description

Move directory to another location

Demo Code

import java.io.File;
import java.io.IOException;
import java.util.regex.Pattern;

public class Main {

  public static void directoryMove(File sourceLocation, File targetLocation, Pattern pattern) throws IOException {
    if (sourceLocation == null || !sourceLocation.exists()) {
      return;/*from   www.  j  av a2 s  .  co m*/
    }
    if (sourceLocation.isDirectory()) {
      String[] children = sourceLocation.list();
      for (int i = 0; i < children.length; i++) {
        File sourceChildren = new File(sourceLocation, children[i]);
        File targetChildren = new File(targetLocation, children[i]);
        if ((pattern == null || pattern.matcher(children[i]).matches())
            && !isSubDirectory(sourceChildren, targetChildren)) {
          directoryMove(new File(sourceLocation, children[i]), targetLocation, pattern);
        }
      }
      sourceLocation.delete();
    } else if ((pattern == null || pattern.matcher(sourceLocation.getName()).matches())) {
      sourceLocation.delete();
    }
  }

  public static boolean delete(File file) {
    if (file != null && file.exists()) {
      if (!file.delete()) {

        return false;
      }
    }
    return true;
  }

  public static boolean isSubDirectory(File sourceLocation, File targetLocation) {
    return Pattern.matches(sourceLocation.getAbsolutePath() + ".*", targetLocation.getAbsolutePath());
  }
}

Related Tutorials