Android:数据库导出适用于模拟器,不适用于手机
我正在尝试将应用程序的数据库导出到 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,但我检查了该文件 - 它存在。 我的手机出了什么问题?
I'm trying to export my application's database to SDcard. It works excellent for emulator, bur not for my phone.
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();
}
}
};
This currentDB.exists()
returns false on the phone, but I checked the file - it exists.
What is wrong with my phone?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您提供的
File
参数错误。来自Android文档:在你的代码中:
它可能是这样的:
这让我惊讶这在模拟器上有效,我对此表示怀疑。它可能会创建一个空文件,因为至少这一行有某种意义,尽管您的变量不是您所命名的:
此外,您可能应该创建一个
finally
块并执行一些FileChannel< /code> 清理那里。
You are supplying
File
wrong parameters. From Android doc:In your code:
It could be like this:
It surprises me this works on emulator, I doubt that. It probably creates an empty file becuase at least this line makes some sort of sense, although your variables are not what you named them:
Also you should probably create a
finally
block and do someFileChannel
clean up in there.