Take the 2-minute tour ×

In my application, when we browse the file from sdcard the file will be .text, .jpg and mpeg4ie video file. I want to store each file type into a particular folder. For example, .text files go to the text folder. My question is when I select the file, how do I check the file extension?

share|improve this question

12 Answers 12

up vote 31 down vote accepted

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:

public class main {
    public static void main(String[] args) {
        String filename = "image.jpg";
        String filenameArray[] = filename.split("\\.");
        String extension = filenameArray[filenameArray.length-1];

Which outputs:

share|improve this answer
assuming an extension exists, I would rather use filename.substring(filename.lastIndexOf('.') + 1) to get the extension. Using regular expression for something simple like this is overkill (and it's slower). –  Ray Zhou Apr 1 '12 at 20:27
rrrrrray, you know what they say about assuming... –  Mike Lentini Apr 1 '12 at 20:55
The point I am trying to get across is to not use regular expression for a simple task like this, not error checking. –  Ray Zhou Apr 1 '12 at 21:15
What if I browse a file from the Gallery of my android phone, where it returns the file name as "content://media/external/images/media/3669". Can I get file name extension in that? @MikeLentini –  CHAKRAVARTHI Jun 26 at 12:10

or you could just do

MimeTypeMap.getFileExtensionFromUrl(myfile.toURL().toString() );

Note: this method is not very reliable though..

share|improve this answer
as File#toURL() is deprecated this should be myfile.toURI().toURL().toString() –  Somatik Nov 6 '11 at 23:06
public static String getFileExt(String FileName)
     return FileName.substring((FileName.lastIndexOf(".") + 1), FileName.length());
share|improve this answer

You can use FilenameUtils from Apache Commons:

String extension = FilenameUtils.getExtension(mFile.getName());
share|improve this answer

You could also do something like the below and use endswith.

public void walkdir(File dir) {
    String txtPattern = ".txt";
    String jpgPattern = ".jpg";
    String mp3Pattern = ".mp3";

    File listFile[] = dir.listFiles();

    if (listFile != null) {
        for (int i = 0; i < listFile.length; i++) {

            if (listFile[i].isDirectory()) {
            } else {
              if (listFile[i].getName().endsWith(txtPattern)){
                                  //put in txt folder
                              }else if (listFile[i].getName().endsWith(jpgPattern)){
                                  // put in jpg folder
                              }else if (istFile[i].getName().endsWith(mp3Pattern)) {
                                  // put in  mp3 folder


Sorry, haven't checked the work but it should do it for you.

share|improve this answer
+1. why does everybody else has to use something aside from this? –  josephus Apr 16 '12 at 9:27
Case sensitive extensions? What about files called readme.TXT etc –  Diederik Oct 30 '12 at 5:22

I have found nice example at docs.oracle.com how to get file extension that return file type extension in lower case or null if there isn't file extension:

     * Get the extension of a file.
    public static String getExtension(File f) {
        String ext = null;
        String s = f.getName();
        int i = s.lastIndexOf('.');

        if (i > 0 && i < s.length() - 1) {
            ext = s.substring(i + 1).toLowerCase();
        return ext;
share|improve this answer

This works for me:

public static String getExtension(String fileName) {
    String encoded;
    try { encoded = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20"); }
    catch(UnsupportedEncodingException e) { encoded = fileName; }
    return MimeTypeMap.getFileExtensionFromUrl(encoded).toLowerCase();

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 when MimeTypeMap.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. It MimeTypeMap does not seem to have entries for .PNG or .JPG.

share|improve this answer
String ext = "", fileName = file.getName().toLowerCase(); try { ext = MimeTypeMap.getFileExtensionFromUrl(fileName); } catch (Exception e) { e.printStackTrace(); } worked for me. –  zanky Feb 18 at 10:43
@zanky That does work a lot of the time, but there are cases (I forget which ones exactly -- it's been several month) where it fails unexpectedly. In my experience, calling Uri.encode on the file name drove the failure case down to zero. –  Xavi Feb 18 at 19:21
@Xavi...ya, you might be right but in my case when i used Uri.Encode it was returning encodes extension of file which was having format something like this 3gp%4a%5D... so i removed encode() method. –  zanky Feb 19 at 5:12
@zanky Huh, that's really weird. I'll keep an eye out for that. Thanks for letting me know. –  Xavi Feb 19 at 7:35
@Xavi..ya sure.. –  zanky Feb 19 at 7:56

Haven't had a chance to run this (so might not work 100%) but it should be what you're looking for:

File files[] = Environment.getExternalStorageDirectory().listFiles();   
for (File f : files)
  String fullPath = f.getAbsolutePath();
  int dot = fullPath.lastIndexOf(".");
  String ext = fullPath.substring(dot + 1);
    //do something with f here
share|improve this answer
Thanx alot Mike And Brenden, –  Nilesh Verma Feb 4 '11 at 9:26
'if (ext.equals(txt))' rather than 'if(ext == "txt")' –  IHeartAndroid May 12 at 8:05
@IHeartAndroid updated, thanks! –  brendan May 12 at 14:55

If you want to get all of the files that have specific extensions in a certain directory:

File[] files = (new File("/sdcard/yourDirectory/").listFiles(new CustomFilter());


class CustomFilter implements FileFilter
//Add the file extensions you want to look for here:
        private String[]    extension   =
                                        { "text", "jpg", "jpeg", "mpeg" };

        public boolean accept(File pathname)
            String name = pathname.getName().toLowerCase();

            for (String anExt : extension)

                if (name.endsWith(anExt))
// A file has been detected with that extension
                    return true;

            return false;

share|improve this answer
public String getExtension(File file) {
        String fileName = file.getName();
        try {
            if (fileName.contains("\\.")) {
                String filenameArray[] = fileName.split("\\.");
                extension = filenameArray[filenameArray.length - 1];
            } else {
                extension = "dir";
        } catch (Exception e) {
            extension = "err";
        return extension;
share|improve this answer

The shortest way to find out file extension is using lastIndexOf('.') assuming file name contains extension. Check the following code

String fileName = "test.jpg";
int i = fileName.lastIndexOf('.');
String fileExtension = fileName.substring(i+1);
Log.v("FILE EXTENSION: ",fileExtension);
share|improve this answer

Here is a method that test all the cases

    String getExtension(String fileName){
        final String emptyExtension = "";
        if(fileName == null){
            return emptyExtension;
        int index = fileName.lastIndexOf(".");
        if(index == -1){
            return emptyExtension;
        return fileName.substring(index + 1);
share|improve this answer

Your Answer


