我正在使用这段代码将文件从内部存储复制到外部存储而不会丢失任何内容:
public static void copyFile(String currentDBPath, String backupDBPath) {
try {
File sd = Environment.getExternalStorageDirectory();
//File data = Environment.getDataDirectory();
if (sd.canWrite()) {
File currentDB = new File(currentDBPath);
File backupDB = new File(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) {
e.printStackTrace();
}
}
当我尝试从内部存储或txt文件复制图像时,它工作正常,没有任何错误,新文件在SD卡中。但是,如果我尝试从/data/data/package/databases/system.sqlite
复制本地数据库文件,它会在给定目标中创建一个新文件,但新数据库文件为空,没有任何表格甚至数据。
为什么只发生数据库文件?
修改:
正如我所注意到的,复制的新数据库文件与原始文件一样大(145KB),但是当我用sqlite浏览器打开它时,没有表,没有数据......没有。
答案 0 :(得分:0)
这就是我们使用的:
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "/data/com.our.package/databases/main.db";
String backupDBPath = "main_" + additionalInfo + ".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();
} else {
Log.e(TAG, "File does not exist: " + currentDBPath);
}
} else {
Log.e(TAG, "SDCard not writable, backup aborted.");
}
} catch (Exception ex) {
Log.e(TAG, "Error backing up database to sdcard.", ex);
return getResources().getInteger(R.integer.unhandled_exception_from_api_service);
}
我们可以将数据库备份到SD卡并使用SQLite浏览器将其读回。