Satpal Yadav
Satpal Yadav

Reputation: 81

How to detect if a filename exists (with any extension) in android

I want to return true if filename exists regardless its extension. I am using following method:

File file = new File(Environment.getExternalStorageDirectory() + Images/","filename.*");
if(file.exists())
{
   return true;
}

There is a jpg file in this directory, if I search for "filename.jpg", it returns true, but in case of "filename.*" it returns false.

Is there any way to return true if filename is same but with any extension?

Upvotes: 1

Views: 189

Answers (1)

Manohar
Manohar

Reputation: 23384

Try this

 File Imagefolder = new File(Environment.getExternalStorageDirectory() + "Images/");
    File[] listOfFiles = Imagefolder.listFiles();

for (File file : listOfFiles)
{
    if (file.isFile())
    {
        String[] filename = file.getName().split("\\.(?=[^\\.]+$)"); //split filename from it's extension
        if(filename[0].equalsIgnoreCase("filename")) 
             // file exists do what ever you want to do

    }
 }

Upvotes: 2

Related Questions