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

时间:2010-01-03 15:45:55

标签: database android backup sd-card

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

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

10 个答案:

答案 0 :(得分:121)

此代码适合我!

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

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

答案 1 :(得分: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();
}

这与上面的例子相反,其中“/”是“我”生命中的20分钟浪费,但我真的应该早点看到它。 Toast会告诉您文件的位置,或者告诉您哪些文件不起作用。

答案 2 :(得分:9)

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

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

答案 3 :(得分:3)

answered一个类似的问题,您可以在SQLiteOpenHelper中添加一种方法。它就像将db文件从某种外部存储器复制到内部应用程序存储一样简单。还有一些额外的代码可以打开并读取db文件,以确保它处于适当的状态,以便Android对其进行数据库调用。

答案 4 :(得分:3)

public static void BackupDatabase() throws IOException
{
    boolean success =true;
    File file = null;
    file = new File(Environment.getExternalStorageDirectory() +"/M.O.L.S_Backup");

    if (file.exists())
    {
        success =true;
    }
    else
    {
        success = file.mkdir();
    }

    if (success)
    {
        String inFileName = "/data/data/com.sygic.sdk.demo/databases/MOLS_DB.s3db";
        File dbFile = new File(inFileName);
        FileInputStream fis = new FileInputStream(dbFile);

        String outFileName = Environment.getExternalStorageDirectory()+"/M.O.L.S_Backup/MOLS_DB.s3db";

        // Open the empty db as the output stream
        OutputStream output = new FileOutputStream(outFileName);

        // Transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = fis.read(buffer))>0) {
            output.write(buffer, 0, length);
        }

        output.flush();
        output.close();
        fis.close();
    }
}

答案 5 :(得分:2)

您必须在申请中提供权限android.permission.WRITE_EXTERNAL_STORAGE。它在无根设备上运行良好。

答案 6 :(得分:1)

我不知道如果手机是否已植根会发生什么,但您应该将文件写入:

/Android/data/{package_name}/files/

无论是否生根,这都会有效。

答案 7 :(得分:1)

如果您是新手,请在数据库适配器中找到您的数据库名称。

请注意,您也可以对SharedPreferences执行此操作,但请记住将Context.MODE_PRIVATE更改为Context.MODE_MULTI_PROCESS。

SharedPreferences_name应如下所示= ExportSP("temp.xml");

String currentPathForSharedPreferences = "/data/"+ context.getPackageName() +"/shared_prefs/"+ SharedPreferences_name;

出口

exportDB("MyDbName");

private void exportDB(String db_name){

File sd = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + 
                File.separator + "Your Backup Folder"+ 
                File.separator );

          boolean success = true;
           if (!sd.exists()) {
               success = sd.mkdir();
           }
           if (success) {

        File data = Environment.getDataDirectory();
       FileChannel source=null;
       FileChannel destination=null;
       String currentDBPath = "/data/"+ context.getPackageName() +"/databases/"+db_name;
       String backupDBPath = db_name;
       File currentDB = new File(data, currentDBPath);
       File backupDB = new File(sd, backupDBPath);
       try {
            source = new FileInputStream(currentDB).getChannel();
            destination = new FileOutputStream(backupDB).getChannel();
            destination.transferFrom(source, 0, source.size());
            source.close();
            destination.close();
            Toast.makeText(this, "Please wait", Toast.LENGTH_SHORT).show();
        } catch(IOException e) {
            e.printStackTrace();
        }
           }}

导入

importDB("MyDbName");

private void importDB(String db_name){
        File sd = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + 
                File.separator + "Your Backup Folder"+ 
                File.separator );
        File data = Environment.getDataDirectory();
       FileChannel source=null;
       FileChannel destination=null;
       String backupDBPath = "/data/"+ context.getPackageName() +"/databases/"+db_name;
       String currentDBPath = db_name;
       File currentDB = new File(sd, currentDBPath);
       File backupDB = new File(data, backupDBPath);
       try {
            source = new FileInputStream(currentDB).getChannel();
            destination = new FileOutputStream(backupDB).getChannel();
            destination.transferFrom(source, 0, source.size());
            source.close();
            destination.close();
            Toast.makeText(this, "Please wait", Toast.LENGTH_SHORT).show();
        } catch(IOException e) {
            e.printStackTrace();
        }
}

答案 8 :(得分:1)

@skeniver's code适合我。我只想添加以下内容:

使用:

String currentDbPath = getApplicationContext().getDatabasePath("{database name}");

它将为您提供数据库路径。最好使用它而不是硬编码路径,例如:

String currentDbPath = "//data//{package name}//databases//{database name}";

答案 9 :(得分:-1)

this.$root