How to check file extension on Android

2020-02-18 03:31发布

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?

标签: android
14条回答
萌系小妹纸
2楼-- · 2020-02-18 03:38

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);
查看更多
一纸荒年 Trace。
3楼-- · 2020-02-18 03:44

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
查看更多
Emotional °昔
4楼-- · 2020-02-18 03:46

Or you could just do:

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

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

查看更多
forever°为你锁心
5楼-- · 2020-02-18 03:47

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;
    }
}
查看更多
Melony?
6楼-- · 2020-02-18 03:48

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.

查看更多
爱情/是我丢掉的垃圾
7楼-- · 2020-02-18 03:48

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);
    }
查看更多
登录 后发表回答