如何在SD卡中进行数据库备份

时间:2016-06-10 16:56:29

标签: android android-database

我已成功备份了我的数据库,但问题是我的备份是保存在内存而非SDcard中。

这是我的代码:

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();
    }
}

2 个答案:

答案 0 :(得分:0)

默认情况下,Context类/ SQLiteOpenHelper类不允许您将数据库文件保存在除内部应用程序存储之外的任何其他位置.ie /data/data/com.you.packagename/databases。您已经获得了一个用于处理SQLite数据库的自定义类或推出了自己的东西 - 在Android Sources目录中获取SQLiteOpenHelper类,如果您知道自己在做什么就编辑它。这是一个自定义implementation of SQLiteOpenHelper you can use.

答案 1 :(得分: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();
   }

}

希望这有帮助。

相关问题