将默认数据库复制到临时数据库中



我想创建一个临时数据库,这是代码:

String PATH = "/data/data/" + appContext.getPackageName() + "/databases/";
            List<File> files = getListFiles(new File(PATH));
            //File dbFile = appContext.getDatabasePath(PreferenceConstants.TEMP_DB_DATABASE_STORE);
            File dbFile = new File(PATH, PreferenceConstants.TEMP_DB_DATABASE_STORE);
            FileInputStream is;
            if (!dbFile.exists()) {
                try {
                    dbFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else
                dbFile.delete();
            try {
                is = new FileInputStream(appContext.getDatabasePath(PreferenceConstants.DB_DATABASE_STORE));
                FileUtils.copyInputStreamToFile(is, dbFile);
            } catch (IOException e) {
                e.printStackTrace();
            }

但是数据库文件夹中没有创建任何文件,为什么?

复制后,我想打开另一个数据库,复制表并将表附加到创建的临时数据库中。

编辑

非常简单的方法:

DatabaseHelper dbIng = new DatabaseHelper(appContextDialog, "temp_database.db");
dbIng.closeDB();

这是我用于导入和导出数据库的方法:别忘了权限。

public void exportDatabase(){
    try
    {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();
        String currentDBPath = "//data//MY.PACKAGE.NAME//databases//MY_DATABASE_NAME";
        String backupDBPath = "MY_DATABASE_FILE.db";
        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(c, c.getResources().getString(R.string.exporterenToast), Toast.LENGTH_SHORT).show();
    }
    catch (Exception e) {
        Toast.makeText(c, c.getResources().getString(R.string.portError), Toast.LENGTH_SHORT).show();
        Log.d("Main", e.toString());
    }
}
public void importDatabase(){
    try
    {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();
        String currentDBPath = "//data//" + "MY.PACKAGE.NAME" + "//databases//" + "MY_DATABASE_NAME";
        String backupDBPath = "MY_DATABASE_FILE.db";
        File backupDB = new File(data, currentDBPath);
        File currentDB = 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(c, c.getResources().getString(R.string.importerenToast), Toast.LENGTH_LONG).show();
    }
    catch (Exception e) {
        Toast.makeText(c, c.getResources().getString(R.string.portError), Toast.LENGTH_SHORT).show();
    }
}

相关内容

  • 没有找到相关文章

最新更新