Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Android code to copy file, directory, and clear directory.
/**
* Copy file from {@code src} to {@code dest}.
*
* @param src
* Source.
* @param dest
* Destination.
*
* @throws IOException
*/
private void copyFile(File src, File dest) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
/**
* Copy dir from {@code src} tor {@code dest}.
*
* @param src
* The target we will write for downloading data.
* @param dest
* Backup location.
*/
private void copyDir(File src, File dest) {
if (src == null || !src.exists()) {
Log.w(TAG, "Can't do copyDir because src doesn't exist or even null by passed.");
} else {
if (!src.isFile()) {
if (!dest.exists()) {
dest.mkdir();
}
} else {
if (!dest.exists()) {
try {
copyFile(src, dest);
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (src.isDirectory()) {
File[] files = src.listFiles();
for (File file : files) {
//Do again for sub-dir or files.
copyDir(file, new File(dest, file.getName()));
}
}
}
}
/**
* Remove the directory.
*
* @param dir
* The location to delete.
*/
private void clearDir(File dir) {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
clearDir(file);
} else {
file.delete();
}
}
dir.delete();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment