Android: should I use MimeTypeMap.getFileExtensionFromUrl()? [bugs]

前端 未结 3 961
情歌与酒
情歌与酒 2021-02-20 06:48

For example, I wanted to get the file Extension from the file URL using the function below:

File name:

Greatest Hits - Lenny Kravitz (Booklet 01) [2000]         


        
3条回答
  •  旧时难觅i
    2021-02-20 07:36

    I use this in my project and it works unless there certain characters in the file name,

    I decided to not go the route of splitting the string myself.

    I made a work around for the issue:

    String ext = MimeTypeMap.getFileExtensionFromUrl(sanitizeFileName(Uri.encode(name)));
    

    And i made this method to sanitize file names:

    public static String sanitizeFileName(String name)
    {
        byte[] invalidChars = new byte[]{34, 60, 62, 124, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 58, 42, 63, 92, 47};
        for(byte i : invalidChars)
        {
            name = name.replace((char)i,'_');
        }
        return name;
    }
    

    The sanitize method is useful for other things as well.

提交回复
热议问题