Skip to content

Instantly share code, notes, and snippets.

@saurabhkpatel
Last active April 30, 2021 03:14
Show Gist options
  • Save saurabhkpatel/16a178992144c380eed34bef4da23f04 to your computer and use it in GitHub Desktop.
Save saurabhkpatel/16a178992144c380eed34bef4da23f04 to your computer and use it in GitHub Desktop.
Move Directory contents : Android/Java
/**
* This utility method moves contents from sourceDirectory to destinationDirectory
*
* @param sourceDirectory : from where to get contents
* @param destinationDirectory : where to move contents
* @return true if success, false otherwise.
*/
public static boolean moveDirectoryContents(@NonNull File sourceDirectory, @NonNull File destinationDirectory) {
if (!sourceDirectory.exists()) {
return false;
}
if (!destinationDirectory.exists() && !destinationDirectory.mkdir()) {
return false;
}
try {
move(sourceDirectory, destinationDirectory);
} catch (IOException e) {
CrashReporter.reportNonFatal(e);
return false;
}
// finally, delete/clean the source directory.
deleteDirectory(sourceDirectory);
return true;
}
private static void move(@NonNull File source, @NonNull File target) throws IOException {
if (source.isDirectory()) {
moveDirectory(source, target);
} else {
moveFile(source, target);
}
}
private static void moveDirectory(@NonNull File source, @NonNull File target) throws IOException {
if (!target.exists() && !target.mkdir()) {
return;
}
for (String file : source.list()) {
move(new File(source, file), new File(target, file));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment