在Android上将数据库备份到SD卡

45

我正在使用下面的代码将备份复制到SDCard,但是我遇到了以下错误:

java.io.IOException: 文件的父目录不可写:/sdcard/mydbfile.db

private class ExportDatabaseFileTask extends AsyncTask<String, Void, Boolean> {
        private final ProgressDialog dialog = new ProgressDialog(ctx);

        // can use UI thread here
        protected void onPreExecute() {
           this.dialog.setMessage("Exporting database...");
           this.dialog.show();
        }

        // automatically done on worker thread (separate from UI thread)
        protected Boolean doInBackground(final String... args) {

           File dbFile =
                    new File(Environment.getDataDirectory() + "/data/com.mypkg/databases/mydbfile.db");

           File exportDir = new File(Environment.getExternalStorageDirectory(), "");
           if (!exportDir.exists()) {
              exportDir.mkdirs();
           }
           File file = new File(exportDir, dbFile.getName());

           try {
              file.createNewFile();
              this.copyFile(dbFile, file);
              return true;
           } catch (IOException e) {
              Log.e("mypck", e.getMessage(), e);
              return false;
           }
        }

        // can use UI thread here
        protected void onPostExecute(final Boolean success) {
           if (this.dialog.isShowing()) {
              this.dialog.dismiss();
           }
           if (success) {
              Toast.makeText(ctx, "Export successful!", Toast.LENGTH_SHORT).show();
           } else {
              Toast.makeText(ctx, "Export failed", Toast.LENGTH_SHORT).show();
           }
        }

        void copyFile(File src, File dst) throws IOException {
           FileChannel inChannel = new FileInputStream(src).getChannel();
           FileChannel outChannel = new FileOutputStream(dst).getChannel();
           try {
              inChannel.transferTo(0, inChannel.size(), outChannel);
           } finally {
              if (inChannel != null)
                 inChannel.close();
              if (outChannel != null)
                 outChannel.close();
           }
        }

     }

非常好的帖子,谢谢。我验证了这段代码确实可以将数据库复制到SD卡中。 - zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
7
你的问题对我来说是一个解决方案。谢谢!;) - Zsolt Safrany
3
这是一个很棒的技巧。但是我想知道如何恢复备份。 - Shajeel Afzal
1
太棒了,为你加100分 :) - chhameed
1个回答

33

你的清单文件中是否定义了权限?

<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接