如何将数据库从SD卡复制到//数据库

时间:2011-11-15 02:09:01

标签: java android database sqlite copy

我很抱歉一个相当绿色的问题,但我找不到解决方案了。

我正在尝试从SD卡备份恢复数据库。以下代码(在SO中提供的略微修改版本)

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

    if (sd.canWrite()) {
        String currentDBPath =
            "\\data\\com.dg\\databases\\" + com.dg.Constants.db_Table;
        String backupDBPath = "com.dg";
        File currentDB = new File(data, currentDBPath);
        File backupDB = new File(sd, backupDBPath);

        if (currentDB.exists()) {
            FileChannel dst = new FileInputStream(currentDB).getChannel();
            FileChannel src = new FileOutputStream(backupDB).getChannel();
            dst.transferFrom(src, 0, src.size());
            src.close();
            dst.close();
        }
        line4.setText("Successful Import");
    }
} catch (Exception e) {
    line4.setText(e.toString());
} 

即使数据库文件未打开,也会抛出NonWriteableChannelException。

2 个答案:

答案 0 :(得分:0)

您的数据通常在

/data/data/com.dg/databases

你需要摆脱路径中的双\。

此外,您使用Environment.getDataDirectory()作为父目录,然后使用" \ data \ com.dg \ databases \"(等)作为文件名。那是完全错误的。

简单的方法可能是“getDatabasePath'在上下文(或活动)中。给它数据库的名称,它应该给你一个文件引用。但是,如果该档案尚未存在,我也不知道会怎么做。

http://developer.android.com/reference/android/content/Context.html#getDatabasePath(java.lang.String

您也可以尝试简单的getDir("数据库",MODE_PRIVATE)'。希望能够返回数据库目录。

最后尝试数据库目录,真的很脏:

File dbDir = new File(getFilesDir().getParentFile(), "databases");

答案 1 :(得分:0)

您的用户/应用程序是否具有//数据库的权限? (如果没有,那么这就是答案。)

也许这可能会告诉你为什么拒绝许可:

IOException: Permission Denied

Bill Mote(来自上面的链接)还指出了以下权限设置:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
相关问题