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

Database 如何将数据库文件备份到Android上的SD卡?,database,android,backup,sd-card,Database,Android,Backup,Sd Card,我想在我的Android应用程序中添加一项功能,自动将数据库备份到数据库 最好的办法是什么?有任何示例或教程可用吗?SQLite数据库是完全独立的文件,并且是可移植的-您只需将整个文件直接复制到SD卡即可 虽然首先我要检查设备中是否安装了SD卡,以及SD卡的路径(使用Environment.getExternalStorageDirectory())。此代码对我有效 try { File sd = Environment.getExternalStorageDirecto

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


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

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


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

此代码对我有效

    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上试用过。

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

/Android/data/{package_name}/files/
无论它是否为根目录,这都会起作用。

我有一个类似于此的问题,您可以在
SQLiteOpenHelper
中放置一个方法。它只需将db文件从某种外部存储器复制到内部应用程序存储器即可。还有一些额外的代码打开并读取db文件,以确保它处于正确的状态,以便Android对其进行数据库调用

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
会告诉你文件放在哪里,或者告诉你它不工作时出了什么问题。

你必须给android.permission.WRITE\u EXTERNAL\u STORAGE权限。它可以在无根设备上正常工作。

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

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();
    }
}
请注意,您也可以对SharedReference执行此操作,但请记住,要将Context.MODE\u PRIVATE更改为Context.MODE\u MULTI\u进程

SharedReferences_名称应如下所示=
ExportSP(“temp.xml”)

出口

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();
        }
}
对我有用。我只想补充以下几点:

使用:

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

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

请注意,如果它在SD卡上,它将不再是你的应用程序的私有文件。@Mirko N:我知道,但人们需要一份备份副本,用于诸如重新安装、手机损坏之类的事情。我可以确认这在无根手机上有效。只需确保添加
currentDB.exists()returnign false。。。。可能b数据库不在sys内存中,但我已成功插入行…并且我通过字符串currentDBPath=db.getPath()获取路径;我使用文件currentDB=getDatabasePath(DatabaseHelper.DATABASE\u NAME);而不是静态referencefilechannel src=newfileoutputstream(currentDB).getChannel();FileChannel dst=新的FileInputStream(backupDB).getChannel();src.transferFrom(dst,0,dst.size());src.close();dst.close();当我这样做的时候,数据库会丢失,并创建一个新的文件和恢复bd,它会是怎样的呢?对于非根设备,备份到sd卡上此位置的问题在于,卸载应用程序时会将其删除。这可能不需要备份。iif(sd.canWrite())对我不起作用。相反,我使用了if(Environment.MEDIA_MOUNTED.equals(state)){我看到了你的示例,它看起来很简洁,好像太简洁了。我很难想出如何使它适应我的代码。我不知道谁的代码更有效,我所知道的是,额外的逻辑/代码或过于简化的代码使我更难理解和适应我的代码。大多数人创建4个单独的“文件”s、 而你的只创建了2个文件。为什么这个特定的主题如此混乱?
@Override
protected void onCreate(Bundle savedInstanceState) {
    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "//data//"+getPackageName()+"//databases//"+DATABASE_NAME+"";
            String backupDBPath = "backup.db";
            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();
    }
}
String currentDbPath = getApplicationContext().getDatabasePath("{database name}");
String currentDbPath = "//data//{package name}//databases//{database name}";