android-从内部存储还原sqlite数据库到appication

时间:2018-08-29 11:52:33

标签: android sqlite android-sqlite

我正在尝试从手机存储中还原数据库,以便在应用程序中使用它。 我已成功将数据库备份到内部存储,但是当我尝试将其还原时,会弹出以下io.exception

  

java.io.IOException:打开失败:ENOENT(没有这样的文件或目录)

如何解决此问题? 但是,我尝试了以下现有解决方案,但是它们没有用 https://github.com/marcj/css-element-queriesAndroid - java.io.FileNotFoundExceptionis it possible backup and RESTORE a database file in android? non root devices

private void restoreDatabase(Context context) {
    String packagename = getPackageName();

    File sdcard = Environment.getExternalStorageDirectory();
    File data = Environment.getDataDirectory();

    try {
        if (sdcard.canWrite()) {
            String currentDBPath = "//data/"+getPackageName() +"/databases/" + DATABASE_NAME;
            String backupDBPath = DATABASE_NAME;
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sdcard, backupDBPath);
            currentDB.createNewFile();

            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(backupDB).getChannel();
                FileChannel dst = new FileOutputStream(currentDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
                Toast.makeText(getApplicationContext(), "Database Restored successfully", Toast.LENGTH_SHORT).show();
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();

    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
    }
}

请不要将此问题标记为重复

1 个答案:

答案 0 :(得分:2)

导出数据库后,您可以使用此功能导入数据库,我拥有它testet,并且工作正常:

private void importDB() {
        String appDataPath = getApplicationContext().getApplicationInfo().dataDir;

        File dbFolder = new File(appDataPath + "/databases");//Make sure the /databases folder exists
        dbFolder.mkdir();//This can be called multiple times.
        //EDITED
        File dbFilePath = new File(appDataPath + "/databases/"+"yourDataBaseName");

        try {
        //EDITED
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "YourBackupFolder","yourDataBaseFileName);
        FileInputStream inputStream = new FileInputStream(file); //use your database name
            OutputStream outputStream = new FileOutputStream(dbFilePath);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer))>0)
            {
                outputStream.write(buffer, 0, length);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();

        } catch (IOException e){
            //handle

            e.printStackTrace();
        }
    }