Android复制文件不适用于本地SQLite文件
我使用这段代码将文件从内部存储复制到外部存储,而不会丢失任何文件:Android复制文件不适用于本地SQLite文件,android,database,file-io,Android,Database,File Io,我使用这段代码将文件从内部存储复制到外部存储,而不会丢失任何文件: publicstaticvoidcopyfile(字符串currentDBPath,字符串backupDBPath){ 试一试{ 文件sd=Environment.getExternalStorageDirectory(); //File data=Environment.getDataDirectory(); if(sd.canWrite()){ File currentDB=新文件(currentDBPath); File
publicstaticvoidcopyfile(字符串currentDBPath,字符串backupDBPath){
试一试{
文件sd=Environment.getExternalStorageDirectory();
//File data=Environment.getDataDirectory();
if(sd.canWrite()){
File currentDB=新文件(currentDBPath);
File backupDB=新文件(backupDBPath);
if(currentDB.exists()){
FileChannel src=newfileinputstream(currentDB).getChannel();
FileChannel dst=新的FileOutputStream(backupDB).getChannel();
transferFrom(src,0,src.size());
src.close();
dst.close();
}
}
}捕获(例外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);
}
我们可以将数据库备份到sd卡,并使用SQLite浏览器将其读回。您可能正在尝试在数据库仍处于打开状态时进行复制吗?我非常确定,在我尝试将其复制到sd卡时,它已关闭。除此之外:文件currentDB=getContext().getDatabasePath(CurrentDBName);你的代码和我的完全相同,我的也没问题。我不太清楚为什么它不能正常工作,但是如果我把代码和图像或txt文件一起使用,一切都可以。我只对sqlite文件有此问题。我在LG MyTouch上有此行为,但在Galaxy选项卡上没有。MyTouch可以复制部分数据,但不是全部,Galaxy选项卡也可以。我不知道是不是这个装置。