2012-11-13 41 views
0

我正在使用下面的代碼嘗試將我的數據庫文件移動到我的SD卡。除了我在sd之下得到紅線外,我沒有任何問題。有任何想法嗎?將我的數據庫移動到SD卡不工作

File data = Environment.getDataDirectory(); 
if (sd.canWrite()) { 
    String currentDBPath = "\\data\\application.package\\databases\\name"; 
    String backupDBPath = "name"; 
    File currentDB = new File(data, currentDBPath); 
    File backupDB = new File(sd, backupDBPath); 
    if (currentDB.exists()) { 
     FileChannel src; 
    try { 
    src = new FileInputStream(currentDB).getChannel(); 
     FileChannel dst = new FileOutputStream(backupDB).getChannel(); 
     try { 
     dst.transferFrom(src, 0, src.size()); 
    src.close(); 
      dst.close(); 
     } catch (IOException e) {              
      e.printStackTrace(); 
     } 
    } catch (FileNotFoundException e) { 
    e.printStackTrace(); 
    } 

enter image description here

enter image description here

+0

你確定斜線的正確性嗎? – teoREtik

+0

目錄是否存在? – Frank

+0

我不確定斜線的正確性。我只是想在這個老問題之後給自己發送一份數據庫的副本。 http://stackoverflow.com/questions/5906703/how-to-attach-database-file-to-an-email-in-android – EGHDK

回答

1

您只能使用一個變量,如果你創建它的一個實例:

把這個放在你的代碼之前:

File sd = Environment.getExternalStorageDirectory(); 
+0

完美。代碼現在運行。 – EGHDK

0

如果你正在使用SQLite數據庫試試這個:

public class _DBHelper extends SQLiteOpenHelper { 

    public boolean backUp() throws Exception 
     { 
      InputStream input = null; 
      OutputStream output = null; 

      try { 
       SQLiteDatabase db = this.getReadableDatabase(); 
       String strSource = db.getPath(); 

       String strDest = Utilities.getAppDocumentsFolder(_context) + "/" 
         + DATABASE_NAME; 

       File fileDest = new File(strDest); 
       if (fileDest.exists()) 
       { 
        fileDest.delete(); 
       } 

       input = new FileInputStream(strSource); 

       output = new FileOutputStream(strDest); 

       byte[] buffer = new byte[1024]; 
       int length; 
       while ((length = input.read(buffer)) > 0) { 
        output.write(buffer, 0, length); 
       } 
      } catch (Exception e) { 
       throw e; 
      } finally 
      { 
       if (output != null) 
       { 
        output.flush(); 
        output.close(); 
       } 
       if (input != null) 
       { 
        input.close(); 
       } 
      } 

      return true; 
     } 
} 
+0

我喜歡那段代碼,但是我遇到了一些問題。我更新了我的問題。 – EGHDK