2014-01-15 101 views
1

我想創建我的數據庫的備份,但我的手機上沒有SDCARD。我想創建在內部存儲備份,但接下來的代碼失敗......無SD卡創建備份數據庫

try { 
     File sd = Environment.getExternalStorageDirectory(); 
     File data = Environment.getDataDirectory(); 
     if (sd.canWrite()) { 
      String currentDBPath = "//storage//sdcard0//MyApp//turnos.db"; 
      String backupDBPath = "turnos.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(); 
      } 
     } mensajeOK("INFO", "Copia creada.");      
    } catch (Exception e) { 
     Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show(); 
    } 

我有權限WRITE_EXTERNAL_STORAGE。

+0

在最新的Android Studio和使用Java 1.8,你得到的密切語句以下編譯器錯誤:'資源泄漏:「<未分配的可關閉值> '永遠不會關閉'。任何想法如何防止這一點? – not2qubit

回答

2

String currentDBPath = "//storage//sdcard0//MyApp//turnos.db"; 

很可能給你大部分的問題。

  1. 你說你沒有SD卡,但正試圖從SD卡上讀取文件。這可能會導致FileNotFoundException。
  2. 文件路徑通常不包含//。它始終是/
  3. 即使您的SD卡存在,它可能不會遵循此路徑。 總是使用Environment.getExternalStorageDirectory()去SD卡
5
  1. 永遠不用硬編碼PATHS

  2. //不是目錄分隔符。 /是。

  3. /storage/sdcard0可能不存在 - 使用Environment.getExternalStorageDirectory(),或getExternalFilesDir()

  4. getDataDirectory()不太可能是一個相關的位置

  5. 現有的數據庫,如果你把它放在正常的地方,可以通過getDatabasePath(),方法可在Context發現(例如,你的Activity

  6. 隨時登錄你的籌碼與TRACES例外,如通過Log.e(),而不是扔掉這些信息,幫助您更好地調試事項

這也許不是所有與你目前的做法存在的問題,但它應該讓你開始。

0

謝謝!有了您的幫助,我已經做了我的數據庫的備份:

try { 
     File sd = Environment.getExternalStorageDirectory(); 
     File data = Environment.getDataDirectory(); 
     if (sd.canWrite()) { 
      String currentDBPath = "data/com.turnos/databases/Horarios"; 
      String backupDBPath = "BackupHorarios"; 
      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(); 
       Toast.makeText(getApplicationContext(), "Import Successful!", Toast.LENGTH_SHORT).show(); 
      } 
     }   
    } catch (Exception e) { 
     Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show(); 
    }