Skip to content

Instantly share code, notes, and snippets.

@asika32764
Forked from frontrangerider2004/dbExport.java
Created December 3, 2023 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asika32764/29f562d7af39a6d850c07c3c4844f170 to your computer and use it in GitHub Desktop.
Save asika32764/29f562d7af39a6d850c07c3c4844f170 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