首页 > 解决方案 > 在 Android 中备份 SQLite 数据库

问题描述

我需要在移动设备的内部存储或 SD 卡中对 SQLite 数据库进行离线备份。但我一无所知,这怎么可能。

我在这里关注了很多线程,但他们建议将数据库复制到另一个位置,这不适合我,也不适合Google Drive.

任何指导都是宝贵的。

标签: androidsqliteandroid-sqlite

解决方案


我使用了这种方法。

public string DATABASE_NAME = "YOUR DATABASE NAME HERE";

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

            if (sd.canWrite()) {
                Log.d("TAG", "DatabaseHandler: can write in sd");
                //Replace with YOUR_PACKAGE_NAME and YOUR_DB_NAME
                String currentDBPath = "filepath here"+DATABASE_NAME;
                //Replace with YOUR_FOLDER_PATH and TARGET_DB_NAME in the SD card
                String copieDBPath = DATABASE_NAME;
                File currentDB = new File(data, currentDBPath);
                File copieDB = new File(sd, copieDBPath);
                if (currentDB.exists()) {
                    Log.d("TAG", "DatabaseHandler: DB exist");
                    @SuppressWarnings("resource")
                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    @SuppressWarnings("resource")
                    FileChannel dst = new FileOutputStream(copieDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                }
            }
        } catch  (Exception e) {
            e.printStackTrace();
        }

    } 

推荐阅读