2012-07-02 106 views
7

我想檢查一個給定的文件是否存在於android sd卡中。我正在嘗試使用絕對路徑創建文件並使用file.exists()進行檢查,但它不起作用。該文件的URL是"file:///mnt/sdcard/book1/page2.html",該文件確實存在。但不知何故file.exists()是不一樣的。如何檢查一個文件是否存在於SD卡中的目錄中

+0

的可能的複製[檢查文件是否在Android上SD卡上存在(https://stackoverflow.com/questions/7697650/check-if-file -sd-card-on-android) –

回答

46
File extStore = Environment.getExternalStorageDirectory(); 
File myFile = new File(extStore.getAbsolutePath() + "/book1/page2.html"); 

if(myFile.exists()){ 
    ... 
} 

這應該工作。

+0

非常感謝!這工作! – working

+0

歡迎您!請將其標記爲已接受,如果它解決了您的問題,謝謝。 –

0
File logFile = new File(
     android.os.Environment.getExternalStorageDirectory() 
       + "/book1/", "page2.tml"); 
if (logFile.exists()) 
    System.out.println("file exists"); 
else 
    System.out.println("file does not exist 
1

您可以檢查如下:

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

做這樣的事情:

File dir = Environment.getExternalStorageDirectory(); 
File yourFile = new File(dir, "your/file/path"); 

if(yourFile.exists()) 
{ 

} 
7

嘗試這樣的:

File file = new File(Environment.getExternalStorageDirectory() + "/book1/page2.html"); 
if (file.exists()) { 
    /*...*/ 
} 

另外,請確保您有:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
清單檔案中的

0
String filepath = getFilesDir().getAbsolutePath(); 
String FileName = "Yourfilename" ; 
File FileMain = new File(filepath, FileName); 
if (FileMain.exists()){ 
do somthing here      
}else{} 
0
File file = new File(path+filename); 
if (file.exists()) 
{ 
//Do something 
} 

檢查,這將工作

相關問題