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 に答える