2016-06-10 110 views
0

我已成功備份了我的數據庫,但問題是我的備份保存在SD卡中的內部存儲器中。如何在SD卡中進行數據庫備份

這裏是我的代碼:

public void exportDatabase() 
{ 
    File sd = Environment.getExternalStorageDirectory(); 
    File data = Environment.getDataDirectory(); 
    String currentDBPath = "/data/" + "com.arpanexample.spm" + "/databases/" + Database.DATABASE_NAME; 
    String backupDBPath = Database.DATABASE_NAME; 
    File currentDB = new File(data, currentDBPath); 
    File backupDB = new File(sd, backupDBPath); 
    try { 
     FileChannel source = new FileInputStream(currentDB).getChannel(); 
     FileChannel destination = new FileOutputStream(backupDB).getChannel(); 
     destination.transferFrom(source, 0, source.size()); 
     source.close(); 
     destination.close(); 
     Toast.makeText(context, "Successfully backup your data", Toast.LENGTH_LONG).show(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

回答

0

默認情況下,Context類/ SQLiteOpenHelper類不要讓您保存您的數據庫文件其他地方,但內部應用程序存儲.IE /data/data/com.you。包名/數據庫。你已經得到了一個自定義的類來處理SQLite數據庫或者推出你的on - 拿到Android Sources目錄中的SQLiteOpenHelper類,並且如果你知道你在做什麼編輯它。這裏是一個自定義implementation of SQLiteOpenHelper you can use.

0

我想嘗試類似的東西,但沒有找到適當的教程。

後來,使用FileCache將內容保存在SD卡中。 緩存將有助於連接到互聯網的應用程序。

package com.sumukh.myApp.anotherjsonparser; 

import java.io.File; 

import android.content.Context; 

public class FileCache { 

private File cacheDir; 

public FileCache(Context context) { 
    // Find the dir to save cached images 
    if (android.os.Environment.getExternalStorageState().equals(
      android.os.Environment.MEDIA_MOUNTED)) 
     cacheDir = new File(
       android.os.Environment.getExternalStorageDirectory(), 
       "AppCache"); 
    else 
     cacheDir = context.getCacheDir(); 
    if (!cacheDir.exists()) 
     cacheDir.mkdirs(); 
} 

public File getFile(String url) { 
    String filename = String.valueOf(url.hashCode()); 
    // String filename = URLEncoder.encode(url); 
    File f = new File(cacheDir, filename); 
    return f; 

} 

public void clear() { 
    File[] files = cacheDir.listFiles(); 
    if (files == null) 
     return; 
    for (File f : files) 
     f.delete(); 
    } 

} 

希望這會有所幫助。