Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

把 Android 應用內的資料庫匯出到 SD 卡

編輯:關於 Android 程式設計

除錯時常需要把 App 私有目錄裡的 SQLite 資料庫拉出來,用工具直接開來看內容。由於 data/data/ 目錄在未取得 root 的情況下無法直接存取,程式內複製一份到外部儲存是最省事的做法。

private void copyDBToSDcrad() {
    String DATABASE_NAME = "資料庫檔名稱";
    String oldPath = "data/data/com.packagename/databases/" + DATABASE_NAME;
    String newPath = Environment.getExternalStorageDirectory()
            + File.separator + DATABASE_NAME;
    copyFile(oldPath, newPath);
}

/**
 * 複製單個檔案
 * @param oldPath 原檔案路徑
 * @param newPath 複製後路徑
 */
public static void copyFile(String oldPath, String newPath) {
    try {
        int bytesum = 0;
        int byteread = 0;
        File oldfile = new File(oldPath);
        File newfile = new File(newPath);
        if (!newfile.exists()) {
            newfile.createNewFile();
        }
        if (oldfile.exists()) {
            InputStream inStream = new FileInputStream(oldPath); // 讀入原檔案
            FileOutputStream fs = new FileOutputStream(newPath);
            byte[] buffer = new byte[1444];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread; // 位元組數,即檔案大小
                fs.write(buffer, 0, byteread);
            }
            inStream.close();
        }
    } catch (Exception e) {
        System.out.println("複製單個檔案操作出錯");
        e.printStackTrace();
    }
}

要點說明

程式碼中的 com.packagename 要換成實際的套件名稱,DATABASE_NAME 換成實際的資料庫檔名(不含 .db 還是含 .db 取決於你的建立方式,通常要帶副檔名)。

複製時採用固定大小的緩衝區迴圈讀寫,避免一次性把整個檔案載入記憶體——資料庫檔通常不小,這樣寫比較穩妥。

另外要注意兩件事:一是需要 WRITE_EXTERNAL_STORAGE 權限,Android 6.0 以上還要動態申請;二是複製這種 I/O 操作務必放在子線程執行,避免阻塞主線程導致 ANR。

如果裝置沒有外部儲存或權限受限,替代方案是把檔案上傳到開發機,或改用 FileProvider 透過 intent 分享出去,在新版 Android 上更為合適。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved