这是我的代码:
try
{
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
String es= System.getenv("EXTERNAL_STORAGE");
if (sd.canWrite())
{
String currentDBPath = "/data/com.my.package/databases/my.db";
String backupDBPath = "my_db_backup.db3";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(es, 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();
}
Toast.makeText(getBaseContext(), backupDB.toString(), Toast.LENGTH_LONG).show();
}
}
catch (Exception e) {
Log.e("APP ERROR", "APP DB Backup", e);
}
全部执行成功。 EXTERNAL_STORAGE 路径是:storage/emulated/legacy。但是当我使用 DDMS 时,EXTERNAL_STORAGE 路径在那里,但没有文件存在。我有一台 HTC One...
更新:11-01-2013 我尝试了下面的所有建议,但没有抛出任何错误,就像在我的代码中一样,这让我相信我的手机只是默默地不允许我将任何内容复制到我的 SD 卡。 我有一部 HTC 手机...在执行“将数据库复制到 SD 卡”代码之前,我需要对我的手机进行任何设置或操作吗?
最佳答案
和我一起试试吧
public void exportDatabse(String databaseName) {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//"+getPackageName()+"//databases//"+databaseName+"";
String backupDBPath = "backupname.db";
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) {
}
}
注意:
只传递数据库名称,不指定扩展名。
像这样:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
exportDatabse("my"); // Correct
exportDatabse("my.db"); // Wrong
}
关于android - 即使没有抛出错误,将数据库复制到 SD 卡也会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19698299/