45

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nilesh Verma
  • 914
  • 1
  • 11
  • 26

13 Answers13

66

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];
        System.out.println(extension);
    }
}

Which outputs:

jpg
Mike Lentini
  • 1,359
  • 12
  • 15
  • 5
    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 01 '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 – Ashokchakravarthi Nagarajan Jun 26 '14 at 12:10
47
public static String getFileExt(String fileName) {
    return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
XXX
  • 8,996
  • 7
  • 44
  • 53
18

Or you could just do:

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

Note: this method is not very reliable though...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pedro
  • 227
  • 3
  • 6
14

You can use FilenameUtils from Apache Commons:

String extension = FilenameUtils.getExtension(mFile.getName());
Phil
  • 35,852
  • 23
  • 123
  • 164
4

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()) {
                walkdir(listFile[i]);
            }
            else {
                if (listFile[i].getName().endsWith(txtPattern)){
                    // Put in txt folder

                } else if (listFile[i].getName().endsWith(jpgPattern.toLowerCase())){
                    // Put in jpg folder

                } else if (istFile[i].getName().endsWith(mp3Pattern.toLowerCase())) {
                    // Put in mp3 folder
                }
            }
        }
    }
}

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matt
  • 1,368
  • 4
  • 16
  • 32
3

I haven't had a chance to run this (so it 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);
    if (ext.equalsIgnoreCase("txt")) // Make sure case is irrelevant
                                     // for your use case; otherwise
                                     // use ext.equals("txt").
    {
        // Do something with f here
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
brendan
  • 29,308
  • 20
  • 68
  • 109
2

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.

Xavi
  • 20,111
  • 14
  • 72
  • 63
  • `String ext = "", fileName = file.getName().toLowerCase(); try { ext = MimeTypeMap.getFileExtensionFromUrl(fileName); } catch (Exception e) { e.printStackTrace(); }` worked for me. – Zankhna Feb 18 '14 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 '14 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. – Zankhna Feb 19 '14 at 05:12
  • @zanky Huh, that's really weird. I'll keep an eye out for that. Thanks for letting me know. – Xavi Feb 19 '14 at 07:35
2

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

String fileName = "test.jpg";
int i = fileName.lastIndexOf('.');
String fileExtension = fileName.substring(i+1);
Log.v("FILE EXTENSION: ", fileExtension);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Umesh
  • 1,609
  • 1
  • 17
  • 28
1

I have found a nice example at docs.oracle.com on how to get the file extension that returns the file type extension in lower case or null if there isn't a 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;
    }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
andrew
  • 6,533
  • 1
  • 22
  • 19
1

Stuff is .endsWith("your extension"):

String whatever = you String;

if (whatever.endsWith("jpg")) {
    // Your jpg code
}
else if(whatever.endsWith("png")) {
   // Your png code
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Umasankar
  • 495
  • 7
  • 6
0

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" };

    @Override
    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;
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MJ93
  • 4,966
  • 8
  • 32
  • 50
0
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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sandeep P
  • 4,291
  • 2
  • 26
  • 45
0

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);
    }
Ilya Gazman
  • 31,250
  • 24
  • 137
  • 216