Search code examples
androidandroid-sdcardandroid-file

check if file on sdcard specific folder


I'm trying to make a simple check if the file exist. I saw similar questions here, but they didn't help. I wrote some code to check if file exist

private String checkIfFileExist(String fileName) {
    String root_sd = Environment.getExternalStorageDirectory().toString();
    File file = new File(root_sd + "/myfolder");
    if (file != null) {
        File list[] = file.listFiles();
        if (list != null && list.length > 0) {
            for (int i = 0; i < list.length; i++) {
                if (list[i].getName().equals(fileName)) {
                    return list[i].getName();
                }
            }
        }
    }
    return null;
}

I try to check if file does not exist then save some files in this folder.I have problem.for example in my folder i have myimage.png file and my code not working perfect because myimage.png also downloaded and i have two files myimage.png and mypng-1.png I don't know what is a wrong in my code


Solution

  • try this

    String path=<YOUR FOLDER PATH + APPEND FILE NAME>;
    File newfile=new File(path);
     if (newfile.exists())
     {
      //Do your task
     }
    

    or simply

    private String checkIfFileExist(String fileName) {
       String root_sd = Environment.getExternalStorageDirectory().toString();
       String root_sd = Environment.getExternalStorageDirectory().toString();
       File file = new File(root_sd + "/myfolder/"+filename);
       if (file.exists())
        {
          return file.getName();
        }else
        {
         return null;
        }
      }