Android 复制文件不适用于本地 SQLite 文件

标签 android database file-io

我正在使用这段代码将文件从内部存储复制到外部存储而不会丢失任何内容:

public static void copyFile(String currentDBPath, String backupDBPath) {
    try {
        File sd = Environment.getExternalStorageDirectory();
        //File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            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();
    }
}

当我尝试从内部存储或 txt 文件复制图像时,它工作正常,没有任何错误,新文件位于 sd 卡中。但是如果我尝试从 /data/data/package/databases/system.sqlite 复制我的本地数据库文件,它会在给定的目的地创建一个新文件,但是新的数据库文件是空的,没有任何表格甚至数据。

知道为什么它只发生在数据库文件上吗?

编辑:

正如我所注意到的,复制的新数据库文件与原始文件一样大 (145KB),但是当我用 sqlite 浏览器打开它时,没有表,没有数据......什么都没有。

最佳答案

这是我们使用的:

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

            if (sd.canWrite()) {
                String currentDBPath = "/data/com.our.package/databases/main.db";
                String backupDBPath = "main_" + additionalInfo + ".db";
                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();
                } else {
                    Log.e(TAG, "File does not exist: " + currentDBPath);
                }
            } else {
                Log.e(TAG, "SDCard not writable, backup aborted.");
            }
        } catch (Exception ex) {
            Log.e(TAG, "Error backing up database to sdcard.", ex);
            return getResources().getInteger(R.integer.unhandled_exception_from_api_service);
        }

我们能够将数据库备份到 sdcard 并使用 SQLite 浏览器读取它。

关于Android 复制文件不适用于本地 SQLite 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9093268/

相关文章:

android - getApplicationContext()、getBaseContext()、getApplication()、getParent()

java - 使用 JComboBox 作为搜索

java - 在 Linux 中使用 java 通过 java.io.File 导入创建文件?

c - `Build Error` 错误 -1073741819 - C

node.js - 获取文件的新内容

java - android: 在 textview 中显示 .txt 文件时出错

java - 如何在没有 Jackson 或 GS​​ON 的情况下更改 POJO 类中的文件名?

android - 无法弄清楚为什么此代码在发送数据包数据时会导致 SIGSEGV

android - 如何在单击按钮时在数据库中添加数据?

mysql - 如何根据外键值有条件地将数据插入表中?