2013-07-03 160 views
7

的文件URI是已知的,如如何检查Android存储中是否存在已知的uri文件?

`file:///mnt/sdcard/Download/AppSearch_2213333_60.apk` 

我要检查,如果该文件可以打开与否的背景下,怎么办?

+0

定义“在后台”? – fge

+0

@fge也许不会阻塞主线程。 – johnchen902

+0

你的问题目前还不清楚,你是否想检查apk是否打开,而不管它是如何打开的,或者你想检查它是否使用单独的线程打开? –

回答

20

检查这样的:

File file = new File("/mnt/sdcard/Download/AppSearch_2213333_60.apk"); 
if (file.exists()) { 
//Do something 
} 

记住删除类似“文件://”等以其它方式使用:

File file = new File(URI.create("file:///mnt/sdcard/Download/AppSearch_2213333_60.apk").getPath()); 
if (file.exists()) { 
    //Do something 
} 

还你在AndroidManifest.xml中为您的应用程序设置适当的权限以访问SD卡:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
1

开始通过提取使用URI文件名:

final String path = URI.create("file:///mnt/sdcard/Download/AppSearch_2213333_60.apk") 
    .getPath(); // returns the path segment of this URI, ie the file path 
final File file = new File(path).getCanonicalFile(); 
// check if file.exists(); try and check if .canRead(), etc 

最好是在这里使用URI,因为它会采取解码文件名中的URI是非法的,但合法所有可能的空间/字符的照顾。如果一个路径的文件是否存在

相关问题