如何能在SD卡编程我备份源码文件?能在、备份、源码、文件

2023-09-04 09:58:39 作者:顾凉兮

当您使用模拟器的sqlite的文件存储在文件夹中靠近主应用程序文件夹,你可以下载它。但是,这个功能不是没有root权限的设备访问。我怎样才能备份在SD卡这一现有的SQLite文件编程

When you use emulator your sqlite file is stored in a folder near your main application folder and you can download it. But this feature is not accessible in not rooted devices. How can I backup this existing sqlite file in SD Card programmatically?

我想在我的应用程序存储在我的SD卡一个特殊的路径该文件的按钮。这可能吗?

I want to have a button in my application that stores this file in a special path in my SD Card. Is it possible?

谢谢

推荐答案

您可以试试这个工作对我来说,记住要在WRITE_EXTERNAL_STORAG​​E许可,您的清单:

You can try this, work for me, remember to get the WRITE_EXTERNAL_STORAGE permission in your manifest:

// 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) {
                }
            }
        }
    }