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:48
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;
}
查看更多
我命由我不由天
3楼-- · 2020-02-18 03:49

You can use FilenameUtils from Apache Commons:

String extension = FilenameUtils.getExtension(mFile.getName());
查看更多
forever°为你锁心
4楼-- · 2020-02-18 03:51

Stuff is .endsWith("your extension"):

String whatever = you String;

if (whatever.endsWith("jpg")) {
    // Your jpg code
}
else if(whatever.endsWith("png")) {
   // Your png code
}
查看更多
乱世女痞
5楼-- · 2020-02-18 03:51
onclick(View view) {
    GetFileExtension(videouri);
    Toast.makeText(this, "Exten: "+GetFileExtension(videouri), Toast.LENGTH_SHORT).show();
}

// Get Extension
public String GetFileExtension(Uri uri){

    ContentResolver contentResolver = getContentResolver();
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();

    // Return file extension
    return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}

Here the videouri variable has a video. I mean:

videouri = data.getData();

under onResultActivity.

You can pass any variable here such as an image, video, MP3, and file/documents. It will work for all type of contents.

It's a corporate code mostly used for commercial purposes.

I'm 100 % sure it will work with confidence...

查看更多
冷血范
6楼-- · 2020-02-18 03:54
public static String getFileExt(String fileName) {
    return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
}
查看更多
\"骚年 ilove
7楼-- · 2020-02-18 03:56

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