1

我有一个应用程序可以创建和更新它自己的 MySQL 数据库。我现在想允许用户导出数据库的副本(用于备份目的),然后在以后再次导入文件。在此过程中,我无需更改数据库的格式。

我不确定最好/最简单的方法来做到这一点。我已经能够让我的应用程序使用下面的代码将数据库导出到 SD 卡,但问题是 - 我怎样才能让我的应用程序再次导入这个文件?

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

        Toast.makeText(getBaseContext(), sd.toString(), Toast.LENGTH_LONG).show();
        Toast.makeText(getBaseContext(), data.toString(), Toast.LENGTH_LONG).show();

        if (sd.canWrite()) {
            String currentDBPath = "//data//"+ packageName +"//databases//"+ class_dbname; //dbList[0];
            String backupDBPath = "//data//"+ class_dbname; //dbList[0];
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            FileChannel src = new FileInputStream(currentDB).getChannel();
            FileChannel dst = new FileOutputStream(backupDB).getChannel();
            dst.transferFrom(src, 0, src.size());
            src.close();
            dst.close();
            Toast.makeText(getBaseContext(), backupDB.toString(), Toast.LENGTH_LONG).show();

        }
    } catch (Exception e) {

        Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();


    }
4

1 回答 1

1

我正在这样做:

     public boolean importDatabase(String dbPath) throws IOException {
    // Close the SQLiteOpenHelper so it will commit the created empty
    // database to internal storage.
    close();
    File newDb = new File(dbPath);
    File oldDb = new File(DB_FILEPATH);
    if (newDb.exists()) {
        FileUtils.copyFile(new FileInputStream(newDb), new FileOutputStream(oldDb));
        // Access the copied database so SQLiteHelper will cache it and mark
        // it as created.
        DBHelper.getWritableDatabase().close();
        return true;
    }
    return false;
}

而“copyFile()”方法是:

public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
    FileChannel fromChannel = null;
    FileChannel toChannel = null;
    try {
        fromChannel = fromFile.getChannel();
        toChannel = toFile.getChannel();
        fromChannel.transferTo(0, fromChannel.size(), toChannel);
    } finally {
        try {
            if (fromChannel != null) {
                fromChannel.close();
            }
        } finally {
            if (toChannel != null) {
                toChannel.close();
            }
        }
    }
}

问候

于 2013-03-28T17:10:44.870 回答