2012-02-01 51 views
3

我使用這段代碼從內部到外部存儲複製文件,而不會丟失任何:Android的副本文件不工作的本地SQLite文件

public static void copyFile(String currentDBPath, String backupDBPath) { 
    try { 
     File sd = Environment.getExternalStorageDirectory(); 
     //File data = Environment.getDataDirectory(); 

     if (sd.canWrite()) { 
      File currentDB = new File(currentDBPath); 
      File backupDB = new File(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(); 
    } 
} 

當我嘗試從內部存儲或TXT複製影像文件工作正常,沒有任何錯誤,新文件在SD卡中。但是,如果我嘗試從/data/data/package/databases/system.sqlite中複製我的本地數據庫文件,它將在給定目標中創建一個新文件,但是新數據庫文件是空的,沒有任何表或甚至數據。

任何想法,爲什麼它只發生在數據庫文件?

編輯:

正如我注意到,這是複製的新的數據庫文件是一樣大,原來的(145KB),但是當我使用SQLite瀏覽器中打開它,沒有桌子,沒有數據...什麼都沒有。

+0

您可能試圖複製數據庫時仍處於打開狀態? – Kuffs 2012-02-01 15:38:04

+0

我很確定,它正在關閉,而我試圖將其複製到SD卡。 – 2012-02-01 15:40:43

+0

除了這個:File currentDB = getContext()。getDatabasePath(CurrentDBName);你的代碼與我的和我的工作完全一樣沒有問題。 – Kuffs 2012-02-01 15:49:58

回答

0

這就是我們使用:

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

      if (sd.canWrite()) { 
       String currentDBPath = "/data/com.our.package/databases/main.db"; 
       String backupDBPath = "main_" + additionalInfo + ".db"; 
       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(); 
       } else { 
        Log.e(TAG, "File does not exist: " + currentDBPath); 
       } 
      } else { 
       Log.e(TAG, "SDCard not writable, backup aborted."); 
      } 
     } catch (Exception ex) { 
      Log.e(TAG, "Error backing up database to sdcard.", ex); 
      return getResources().getInteger(R.integer.unhandled_exception_from_api_service); 
     } 

我們能夠將數據庫備份到sd卡和使用SQLite瀏覽器讀取它。

相關問題