我正在尝试将我的应用程序的数据库导出到 SD 卡。它非常适合模拟器,但不适用于我的手机。
OnClickListener mExportListener = new OnClickListener(){
public void onClick(View v){
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "\\data\\com.mypck.myapp\\databases\\database";
String backupDBPath = "database.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{
String msg = activity.getResources().getString(R.string.something_wrong);
Toast toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG);
toast.show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
此 currentDB.exists()
在手机上返回 false,但我检查了文件 - 它存在。
我的手机出了什么问题?
最佳答案
您提供的 File
参数有误。来自 Android 文档:
File(String parent, String child)
parent - The parent pathname string
child - The child pathname string
在你的代码中:
parent => \\data
child => \\data\\com.mypck.myapp\\databases\\database
resulting path => \\data\\data\\com.mypck.myapp\\databases\\database => wrong
可能是这样的:
String sd = Environment.getExternalStorageDirectory();
if (sd.canWrite()) {
String currentDBPath = "data/data/com.mypck.myapp/databases/your_database_name.db";
String backupDBPath = sd + "/your_output_file_name.db";
File currentDB = new File(currentDBPath);
File backupDB = new File(backupDBPath);
/* ... */
令我惊讶的是这在模拟器上有效,我对此表示怀疑。它可能会创建一个空文件,因为至少这一行有某种意义,尽管您的变量不是您命名的:
File backupDB = new File(sd, backupDBPath);
您还应该创建一个 finally
block 并在其中做一些 FileChannel
清理工作。
关于Android:数据库导出适用于模拟器,不适用于手机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8166920/