2013-07-03 157 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是非法的,但合法所有可能的空間/字符的照顧。如果一個路徑的文件是否存在

相關問題