2011-10-08 96 views

回答

51

這應該做的伎倆,我把它換成硬編碼的SD卡參考推薦的API調用getExternalCacheDir()

File file = new File(getExternalCacheDir(), "mytextfile.txt"); 
if (file.exists()) { 
    //Do action 
} 
+0

非常感謝你 – androiddevs78

+4

請注意存在與否:getExternalCacheDir ()可能不是你想要的。如果您想要在sd上安裝一個目錄,在卸載應用程序後(例如「緩存」目錄),請使用getExternalCacheDir()。但是,如果你想要SD卡的頂級目錄,那麼你可能會更好地使用:File sdDir = new File(Environment.getExternalStorageDirectory()。getPath()); – DEzra

0

您必須創建一個文件,並將其設置爲必需的文件,並檢查它是否存在。

String FILENAME="mytextfile.txt"; 
File fileToCheck = new File(getExternalCacheDirectory(), FILENAME); 
if (fileToCheck.exists()) { 
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE); 
} 

玩得開心!

+0

最好不要使用SD卡的硬編碼參考,請參閱我以前的答案,以獲得訪問外部存儲的更好方法。 – Ljdawson

0

如果指定的文件不存在,構造函數FileOutputStream將拋出FileNotFound異常。有關更多信息,請參閱Oracle documentation

此外,請確保您有權限access the SD card

0

檢查是否與布爾類型的條件一樣

File file = new File(path+filename); 
if (file.exists() == true) 
{ 
//Do something 
} 
+0

上面的代碼中'== true'是redondant。你可以用'if(file.exists())'代替。 – Slander

2

* 使用此您可以檢查該文件是在SD卡*

File file = new File(sdcardpath+ "/" + filename); 
if (file.exists()) 
{ 

}