Created
January 12, 2015 21:47
-
-
Save XinyueZ/5d287486bb27990db306 to your computer and use it in GitHub Desktop.
Android code to copy file, directory, and clear directory.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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