尝试将db导出到SDCARD

时间:2011-09-04 15:01:18

标签: android export

我对Android很新,我正在尝试将我的数据库导出到SDCARD,以便将其导入到我的其他应用程序中。

有什么建议吗?

提前完成。

2 个答案:

答案 0 :(得分:1)

导出示例:

public void exportDB(){
    try {
        File sd = Environment.getExternalStorageDirectory();
        if (sd.canWrite()) {
            String currentDBPath = "data/data/com.mypack.myapp/databases/mydb.db";
            String backupDBPath = sd + "/filename.db";
            File currentDB = new File(currentDBPath);
            File backupDB = new File(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) {
        e.printStackTrace();
    }
}

导入与导出非常相似:

public void importDB(){
    try {
        File sd = Environment.getExternalStorageDirectory();
        if (sd.canWrite()) {
            String currentDBPath = sd + "/filename.db";
            String backupDBPath = "data/data/com.mypack.myapp/databases/mydb_2.db";
            File currentDB = new File(currentDBPath);
            File backupDB = new File(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) {
        e.printStackTrace();
    }
}

答案 1 :(得分:0)

虽然这可能不是您尝试执行的操作的最佳解决方案,但您的数据库已存储在/data/data/your.package.name中。您只需将其作为文件加载并保存到SD卡即可。点击此处查看执行此操作的代码:

http://www.screaming-penguin.com/node/7749