How can I copy database to the sd card?


How could I copy a database that I store inside my own app to the sd card, for example if I create a folder within app\src\main\res and store the bd in that directory, as I could copy it to the sd card. ?

asked by Gerardo Díaz Rodríguez 17.05.2017 в 05:08

1 answer


You can access the SD card in this way:

File sd = Environment.getExternalStorageDirectory();

To the data of your application

File data = Environment.getDataDirectory();

The path of your database

String pathData = "//data//"+getPackageName()+"//databases//"+NOMBRE_BASE_DE_DATOS+"";

Create a variable with the value of the name you want to give to the backup

String backupDBPath = "backupdatabase.db";  

Obtain and / or create the previously named files

File currentDB = new File(data, pathData );
File backupDB = new File(sd, backupDBPath);

Verify that your database does exist, obtain the file and create / transfer the backup file within the sd.

if (currentDB.exists()) {
    FileChannel src = new FileInputStream(currentDB).getChannel();
    FileChannel dst = new FileOutputStream(backupDB).getChannel();
    dst.transferFrom(src, 0, src.size());


You must add the permission WRITE_EXTERNAL_STORAGE to your Manifest and if you are working with versions 6.0 or higher, remember to capture the permission and if not, ask the user.

answered by 15.06.2017 в 22:10