如何以编程方式备份​​SD卡中的sqlite文件?

Bob*_*obs 5 database sqlite android store sd-card

当您使用模拟器时,您的sqlite文件存储在主应用程序文件夹附近的文件夹中,您可以下载它.但是,在没有root设备的情况下无法访问此功能.如何以编程方式备份​​SD卡中现有的sqlite文件

我希望在我的应用程序中有一个按钮,将该文件存储在SD卡的特殊路径中.可能吗?

谢谢,

小智 16

你可以尝试这个,为我工作,记得在你的清单中获得WRITE_EXTERNAL_STORAGE权限:

// Copy to sdcard for debug use
    public static void copyDatabase(Context c, String DATABASE_NAME) {
        String databasePath = c.getDatabasePath(DATABASE_NAME).getPath();
        File f = new File(databasePath);
        OutputStream myOutput = null;
        InputStream myInput = null;
        Log.d("testing", " testing db path " + databasePath);
        Log.d("testing", " testing db exist " + f.exists());

        if (f.exists()) {
            try {

                File directory = new File("/mnt/sdcard/DB_DEBUG");
                if (!directory.exists())
                    directory.mkdir();

                myOutput = new FileOutputStream(directory.getAbsolutePath()
                        + "/" + DATABASE_NAME);
                myInput = new FileInputStream(databasePath);

                byte[] buffer = new byte[1024];
                int length;
                while ((length = myInput.read(buffer)) > 0) {
                    myOutput.write(buffer, 0, length);
                }

                myOutput.flush();
            } catch (Exception e) {
            } finally {
                try {
                    if (myOutput != null) {
                        myOutput.close();
                        myOutput = null;
                    }
                    if (myInput != null) {
                        myInput.close();
                        myInput = null;
                    }
                } catch (Exception e) {
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)