2016-11-26 54 views
-1

請幫我,我該怎麼辦。 我想通過代碼將數據庫導出到SD卡,但它不會在SD卡中創建數據庫文件。我想通過代碼將數據庫導出到SD卡,但它不會創建SD卡中的db文件

我試過的代碼。

// error in getting the " File dir = new File(getStorageBasedirectory().getAbsolutePath+ "/backup");" 
public File getBackupData`enter code here`baseFile() { 
     File dir = new File(Environment.getExternalStorageDirectory()+ "/backup"); 
     if (!dir.exists()) { 
      dir.mkdirs(); 
     } 
     return new File(dir, DATABASE_NAME); 
    } 
    public final boolean backupDatabase() { 
     File from = context.getDatabasePath(DATABASE_NAME); 
     File to = this.getBackupDatabaseFile(); 
     try { 
      FileUtils.copyFile(from, to); 
      return true; 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      Toast.makeText(context, "Error while copying file", Toast.LENGTH_SHORT).show(); 
     } 
     return false; 
    } 
    public static void copyFile(File src, File dst) throws IOException { 
     FileInputStream in = new FileInputStream(src); 
     FileOutputStream out = new FileOutputStream(dst); 
     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(); 
     } 
    } 
+1

你可以請把你的代碼 – Raju

回答

0

試試這個代碼

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

    if (sd.canWrite()) { 
     String currentDBPath = "//data//{package name}//databases//{database name}"; 
     String backupDBPath = "{database 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) { 
} 
+0

我已經使用這個代碼,但不顯示的數據庫文件 –

+0

檢查該文件http://pastebin.com/1Y4YTj6b –

+0

它不適合我先生 –