我想檢查SD卡上是否存在文本文件。文件名是mytextfile.txt。以下是代碼:檢查Android上的SD卡上是否存在文件
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
如何檢查此文件是否存在?
我想檢查SD卡上是否存在文本文件。文件名是mytextfile.txt。以下是代碼:檢查Android上的SD卡上是否存在文件
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
如何檢查此文件是否存在?
這應該做的伎倆,我把它換成硬編碼的SD卡參考推薦的API調用getExternalCacheDir():
File file = new File(getExternalCacheDir(), "mytextfile.txt");
if (file.exists()) {
//Do action
}
您必須創建一個文件,並將其設置爲必需的文件,並檢查它是否存在。
String FILENAME="mytextfile.txt";
File fileToCheck = new File(getExternalCacheDirectory(), FILENAME);
if (fileToCheck.exists()) {
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
}
玩得開心!
最好不要使用SD卡的硬編碼參考,請參閱我以前的答案,以獲得訪問外部存儲的更好方法。 – Ljdawson
如果指定的文件不存在,構造函數FileOutputStream
將拋出FileNotFound
異常。有關更多信息,請參閱Oracle documentation。
此外,請確保您有權限access the SD card。
檢查是否與布爾類型的條件一樣
File file = new File(path+filename);
if (file.exists() == true)
{
//Do something
}
上面的代碼中'== true'是redondant。你可以用'if(file.exists())'代替。 – Slander
* 使用此您可以檢查該文件是在SD卡*
File file = new File(sdcardpath+ "/" + filename);
if (file.exists())
{
}
非常感謝你 – androiddevs78
請注意存在與否:getExternalCacheDir ()可能不是你想要的。如果您想要在sd上安裝一個目錄,在卸載應用程序後(例如「緩存」目錄),請使用getExternalCacheDir()。但是,如果你想要SD卡的頂級目錄,那麼你可能會更好地使用:File sdDir = new File(Environment.getExternalStorageDirectory()。getPath()); – DEzra