Dinash
Dinash

Reputation: 3047

How to back up .db files to the SDCard?

Is it possible to copy the .db file such as mmssms.db or user_dict.db to the SDCard?

If it is possible then all I need to do is, read the db file and write it to the SDCard.

Upvotes: 0

Views: 1003

Answers (2)

Android
Android

Reputation: 9023

// Local database
    InputStream input = new FileInputStream(from);

    // create directory for backup
    File dir = new File(DB_BACKUP_PATH);
    dir.mkdir();

    // Path to the external backup
    OutputStream output = new FileOutputStream(to);

    // transfer bytes from the Input File to the Output File
    byte[] buffer = new byte[1024];
    int length;
    while ((length = input.read(buffer))>0) {
        output.write(buffer, 0, length);
    }

    output.flush();
    output.close();
    input.close();

Upvotes: 0

evilone
evilone

Reputation: 22740

You could start with this sample:

try {
   File sd = Environment.getExternalStorageDirectory();
   File data = Environment.getDataDirectory();

   if (sd.canWrite()) {
      String currentDBPath = "\\data\\{package name}\\databases\\{database name}";
      String backupDBPath = "{database name}";
      File currentDB = new File(data, currentDBPath);
      File backupDB = new File(sd, backupDBPath);

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

         dst.transferFrom(src, 0, src.size());

         src.close();
         dst.close();
      }
   }
} catch (Exception e) {
   // exception
}

Upvotes: 1

Related Questions