如何将.db文件备份到SDCard?

时间:2011-06-22 08:28:53

标签: android database

是否可以将.db文件(例如mmssms.dbuser_dict.db)复制到SD卡?

如果有可能,那么我需要做的就是读取db文件并将其写入SD卡。

2 个答案:

答案 0 :(得分:1)

你可以从这个样本开始:

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
}

答案 1 :(得分:1)

// 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();