Skip to content

Instantly share code, notes, and snippets.

@frontrangerider2004
Created October 17, 2017 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save frontrangerider2004/6685396cb0133491c0066fcaea700ade to your computer and use it in GitHub Desktop.
Save frontrangerider2004/6685396cb0133491c0066fcaea700ade to your computer and use it in GitHub Desktop.
Export all SQLite database files from your Android Application's private data directory to the SD Card
public static void exportAllDatabases(final Context context) {
Log.d(LOG_TAG, "exportAllDatabases: ");
File sd = Environment.getExternalStorageDirectory();
if (sd.canWrite()) {
final File[] databases = new File(context.getFilesDir().getParentFile().getPath() + "/databases").listFiles();
for (File databaseFile: databases) {
final String backupFilename = databaseFile.getName() + "-" + Build.SERIAL +
"-" + System.currentTimeMillis() + ".db";
File backupFile = new File(sd, backupFilename);
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
Log.d(LOG_TAG, "Backing up: " + databaseFile + " to file: " + backupFile);
inputChannel = new FileInputStream(databaseFile.getAbsolutePath()).getChannel();
outputChannel = new FileOutputStream(backupFile).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputChannel != null) {
try {
inputChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputChannel != null) {
try {
outputChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
} else {
Log.w(LOG_TAG, "Can't write to sdcard");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment