如何在SD卡中进行数据库备份
问题描述:
我已成功备份了我的数据库,但问题是我的备份保存在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();
}
}
答
默认情况下,Context类/ SQLiteOpenHelper类不要让您保存您的数据库文件其他地方,但内部应用程序存储.IE /data/data/com.you。包名/数据库。你已经得到了一个自定义的类来处理SQLite数据库或者推出你的on - 拿到Android Sources目录中的SQLiteOpenHelper类,并且如果你知道你在做什么编辑它。这里是一个自定义implementation of SQLiteOpenHelper you can use.
答
我想尝试类似的东西,但没有找到适当的教程。
后来,使用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();
}
}
希望这会有所帮助。