代码之家  ›  专栏  ›  技术社区  ›  CodeFusionMobile

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

  •  56
  • CodeFusionMobile  · 技术社区  · 15 年前

    我想在我的Android应用程序中添加一个自动备份 SQLite 数据库到 SD card .

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

    10 回复  |  直到 7 年前
        1
  •  9
  •   Christopher Orr    15 年前

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

    不过,首先我会检查设备中是否安装了SD卡,以及它的路径(使用 Environment.getExternalStorageDirectory() )

        2
  •  120
  •   sajal    12 年前

    这个代码对我有用!

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

    有人知道这是否适用于非根电话吗?我只在一个根深蒂固的g1上尝试过。

        3
  •  20
  •   Andrew T.    11 年前
    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 会告诉你文件放在哪里,或者当文件不起作用时告诉你出了什么问题。

        4
  •  3
  •   Community Mohan Dere    8 年前

    answered 类似于此的问题,您可以在 SQLiteOpenHelper .它与将数据库文件从某种外部存储复制到内部应用程序存储一样简单。还有一些额外的代码可以打开和读取数据库文件,以确保Android对其进行数据库调用时处于正确的状态。

        5
  •  3
  •   Peter Mortensen Pieter Jan Bonestroo    9 年前
    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();
        }
    }
    
        6
  •  2
  •   Peter Mortensen Pieter Jan Bonestroo    9 年前

    你必须给予许可 android.permission.WRITE_EXTERNAL_STORAGE 在您的应用程序中。它可以在未配置的设备上正常工作。

        7
  •  1
  •   the Tin Man    14 年前

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

    /Android/data/{package_name}/files/
    

    不管它是否扎根,这都会起作用。

        8
  •  1
  •   ORY    9 年前

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

    请注意,您也可以为共享的引用执行此操作,但请记住,将context.mode_private更改为context.mode_multi_进程。

    sharedreferences的名称应如下所示= 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();
            }
    }
    
        9
  •  1
  •   Adinia Nirmal Dhara    7 年前

    @skeniver's code 为我工作。我只想添加以下内容:

    用途:

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

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

    String currentDbPath = "//data//{package name}//databases//{database name}";
    
        10
  •  -1
  •   Quintin Balsdon    8 年前
    @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();
        }
    }