How to check if a file exists in a directory in sd card

半腔热情 提交于 2019-12-21 11:31:12

问题


I want to check whether a given file exists in android sd card. I am trying it out with creating a file using the absolute path and checking with file.exists() but its not working. The URL for the file is "file:///mnt/sdcard/book1/page2.html" and the file does exist. But somehow file.exists() isn't showing the same.


回答1:


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

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

This should work.




回答2:


Try like this:

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

Also make sure you have:

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

in your manifest file.




回答3:


You can check as follows:

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



回答4:


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



回答5:


Do something like this :

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

if(yourFile.exists())
{

}



回答6:


String filepath = getFilesDir().getAbsolutePath(); 
String FileName = "Yourfilename" ;
File FileMain = new File(filepath, FileName); 
if (FileMain.exists()){ 
do somthing here                     
}else{}



回答7:


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

checked, this will work



来源:https://stackoverflow.com/questions/11292359/how-to-check-if-a-file-exists-in-a-directory-in-sd-card

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!