是否可以将数据库文件保存到 SD 卡?

2022-01-24 00:00:00 database save android java sd-card

可能重复:
是否可以将数据库文件复制到 SD 卡?

我的 Android 手机上有一个数据库,我需要将信息存入 SD 卡.

I have a database on my Android phone, and I need to get the information onto an SD card.

是否可以将数据库文件以可读状态保存到 SD 卡上?我无法找到有关如何执行此操作的任何信息.我知道数据库的名称和字段等...

Is it possible to save the database file onto the SD card in a readable state? I haven't been able to find any information on how to do this. I know the name of the database, and fields etc...

我找到了一些展示如何保存到 SD 卡的示例,但并不完全符合我的需要.

I've found some examples that show how to save to SD cards, but not exactly what I need.

将数据库文件复制到 SD 卡的一些源代码将是完美的.

Some source code that copies the database file to an SD card would be perfect.

希望这个问题足够清楚.

Hopefully this question is clear enough.

推荐答案

是的.这是我使用的功能:

Yes. Here is the function that i use:

public void copyDBToSDCard() {
    try {
        InputStream myInput = new FileInputStream("/data/data/com.myproject/databases/"+DATABASE_NAME);

        File file = new File(Environment.getExternalStorageDirectory().getPath()+"/"+DATABASE_NAME);
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                Log.i("FO","File creation failed for " + file);
            }
        }

        OutputStream myOutput = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+DATABASE_NAME);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
        Log.i("FO","copied");

    } catch (Exception e) {
        Log.i("FO","exception="+e);
    }


}

对于我从事的项目,我在主屏幕中放置了一个菜单选项,我可以随时从中调用此功能.然后,我会将数据库移动到我的桌面并使用 FireFox 的 SQLite Manager 插件打开它.

For a project that I worked on, I put a menu option in the home screen that I could call this function from at any time. Then, I'd move the database to my desktop and open it up with the SQLite Manager plugin for FireFox.

相关文章