In my application, when we browse the file from the SD card, the files will be .text, .jpg and mpeg4ie video files.
I want to store each file type into a particular folder. For example, .text files go to the text folder. When I select the file, how do I check the file extension?
The shortest way to find out a file extension is using
lastIndexOf('.')
, assuming the file name contains an extension. Check the following code:I would get the file name as a String, split it into an array with "." as the delimiter, and then get the last index of the array, which would be the file extension. For example:
Which outputs:
Or you could just do:
Note: this method is not very reliable though...
If you want to get all of the files that have specific extensions in a certain directory:
This works for me:
When the file is
/mnt/sdcard/boomerang/2013-06-18_12:08:53.txt
,"txt"
is returned.Note the
URLEncoder.encode
and.repalce
calls should fix any reliability issues you might see whenMimeTypeMap.getFileExtensionFromUrl
is called by itself. For example, without the encoding and replace calls, file names such as"Test Image!.jpg"
return empty strings. Also make sure the file name is lowercased. ItMimeTypeMap
does not seem to have entries for.PNG
or.JPG
.Here is a method that test all the cases