2013-08-16 30 views
0

我的應用程序有一個數據庫。現在我想複製數據庫備份到標準用戶文件夾或SD卡。 在Eclipse中我發現它在數據/數據/數據庫 - 但真正的設備上的數據庫在哪裏?Android如何訪問數據庫

回答

0

試試這個...只是替換lite.db它是我的數據庫的名稱。

private void copyDB() { 
    File dir = new File(Environment.getExternalStorageDirectory() 
      + "/backup"); 
    if (!dir.exists()) { 
     dir.mkdirs(); 
    } 
    File from = new File("/data/data/" + getPackageName() + "/databases/", 
      "lite.db"); 
    File to = new File(dir, "lite.db"); 
    try { 
     FileInputStream in = new FileInputStream(from); 
     FileOutputStream out = new FileOutputStream(to); 
     FileChannel fromChannel = null, toChannel = null; 
     try { 
      fromChannel = in.getChannel(); 
      toChannel = out.getChannel(); 
      fromChannel.transferTo(0, fromChannel.size(), toChannel); 
     } finally { 
      if (fromChannel != null) 
       fromChannel.close(); 
      if (toChannel != null) 
       toChannel.close(); 
     } 
    } catch (IOException e) { 
     Log.e("backup", "Error backuping up database: " + e.getMessage(), e); 
    } 

} 

還不忘加權限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
0

Eclipse顯示的路徑是正確的,絕對路徑由設備改變,如果你已經植根設備,你可以看到文件。始終在/ data/data/*中。如果你的設備沒有根,你不能看到這個文件

0

IN REAL設備你不能訪問這些文件!

+0

這是錯誤的。您無法從資源管理器訪問目錄,但可以通過程序訪問。 – Namenlos

+0

Ofcourse只有當你有root權限..檢查出來.. http://stackoverflow.com/questions/7268908/access-the-phone-internal-storage-to-push-in-sqlite-database-file – Exceptional

+0

你沒有root權限也可以訪問。看看我的答案。 – Namenlos

0

數據庫存儲在設備中的數據目錄,你可以用Environment.getDataDirectory()得到它。在此目錄中,您的數據庫存儲在以下路徑下:/data/YOUR.PACKAGE.NAME/databases/YOUR.DB.NAME

這裏是一個小例子,如何你可以備份你的數據庫:

public void exportDB() { 
    try { 
     File sd = Environment.getExternalStorageDirectory(); 
     File data = Environment.getDataDirectory(); 
     if(sd.canWrite()) { 
      String currentDBPath = "//data//com.example.packagename//databases//" + DB_NAME; 
      String backupDBPath = DB_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) { 
     e.printStackTrace(); 
    } 
} 

當然,你還需要<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

之後,您可以通過給定的文件名找到你的數據庫在你的SD 「DB_NAME」。

+0

謝謝@ Namenlos和沙代碼 - 非常有幫助 –