【发布时间】:2013-11-18 05:58:30
【问题描述】:
在我的应用程序中,用户单击按钮后,下载管理器开始从 Internet 下载文件并使用以下代码将其保存到内部 sd 卡:
void startDownload()
{
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdirs();
download_req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle(PersianReshape.reshape("Downloading"))
.setDescription(PersianReshape.reshape("currently downloading the file..."))
.setDestinationInExternalPublicDir(Environment.getExternalStorageDirectory().getAbsolutePath() , packageId + ".sqlite");
download_ID = mgr.enqueue(download_req);
}
下载后,我计划每次使用此代码运行应用程序时检查它的存在性:
String DatabaseAddress =
Environment.getExternalStorageDirectory().getAbsolutePath() +
"/ee.sqlite";
File file = new File(DatabaseAddress);
Log.d("PATH File: ", DatabaseAddress);
if (file.exists()){
Toast.makeText(getApplicationContext(), "found", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "not found", Toast.LENGTH_SHORT).show();
}
现在,当我运行此代码时,它会返回“未找到”消息,而文件已经存在(我使用文件管理器检查了它的存在)。
我测试的设备是nexus 7,保存下载文件的路径是:/storage/emulated/0/ee.sqlite
ee.sqlite 是下载文件的文件名。
/storage/emulated/0/ 是app返回的默认路径
为此代码添加到清单的权限是:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
问:为什么file.exists()有文件时返回false?
更新: 当我使用硬编码时
File temp = new File("/sdcard/storage/emulated/0/", "ee.sqlite");
它有效,但是当我使用 Environment.getExternalStorageDirectory().getPath() 时它不起作用。
【问题讨论】:
-
尝试打印
file.getAbsolutePath():它们(文件)可能位于不同的目录中。另一个可能的原因是权限,但我不认为是因为权限。 -
file.getAbsolutePath 返回与 file.getPath() 相同的地址。
-
我的意思是下载的目的路径和你检查是否存在的路径可能不同。
-
顺便说一句,你有没有提到在你的代码中你在一个地方使用 getExternalStoragePublicDirectory() 而在另一个地方使用 getExternalStorageDirectory()?
-
如果它们相同,
Log.d("~~~", "----" + new File(file.getAbsolutePath()).exists())应该打印 true 而Log.d("~~~", "----" + file.exists())打印 false。这将是荒谬的,也意味着一个错误。
标签: java android android-networking android-file