我正在使用这段代码将文件从内部存储复制到外部存储而不会丢失任何内容:
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 浏览器打开它时,没有表,没有数据......什么都没有。
最佳答案
这是我们使用的:
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);
}
我们能够将数据库备份到 sdcard 并使用 SQLite 浏览器读取它。
关于Android 复制文件不适用于本地 SQLite 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9093268/