如何将数据库文件备份到Android上的SD卡?

Cod*_*ile 58 database backup android sd-card

我想在我的Android应用程序中添加一项功能,自动将SQLite数据库备份到SD卡.

最好的方法是什么?有任何示例或教程可用吗?

ske*_*ver 122

这段代码适合我!

    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "//data//{package name}//databases//{database name}";
            String backupDBPath = "{database name}";
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(currentDB).getChannel();
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
            }
        }
    } catch (Exception e) {
    }
Run Code Online (Sandbox Code Playgroud)

有谁知道这是否适用于非root手机?我只在一个有根据的G1上尝试过它.

  • 我可以确认这对非根电话有效.只需确保添加`<uses-permission android:name ="android.permission.WRITE_EXTERNAL_STORAGE"> </ uses-permission>` (19认同)
  • 我使用File currentDB = getDatabasePath(DatabaseHelper.DATABASE_NAME); 而不是静态的反抗 (10认同)

小智 20

try {
    File sd = Environment.getExternalStorageDirectory();
    File data = Environment.getDataDirectory();

    if (sd.canWrite()) {
        String currentDBPath = "//data//"+ packageName +"//databases//"+dbList[0];
        String backupDBPath = 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();
}
Run Code Online (Sandbox Code Playgroud)

这与上面的例子相反,上面的例子中"/"被浪费了20分钟我的生活,但我真的应该早点看到它.该Toast会告诉你该文件已经到位或告诉你什么是错误的,当它不工作.


Chr*_*Orr 9

SQLite数据库是完全独立的文件并且是可移植的 - 您只需将整个文件直接复制到SD卡即可.

虽然我首先要检查设备中是否安装了SD卡,以及它的路径是什么(使用Environment.getExternalStorageDirectory()).