Tarkenfire
Tarkenfire

Reputation: 199

How to get the MIME-type of oddly-named files?

I'm writing a basic file browser that changes the icon used for files displayed depending on the MIME type of the file, but I'm having trouble finding the MIME type of some files, and I'm not sure why, the code I'm using to find the MIME Type is thus:

    private String getFileMimeType(File file)
{
    Uri fileUri = Uri.fromFile(file);
    String ext = MimeTypeMap.getFileExtensionFromUrl(fileUri.toString());
    return mtm.getMimeTypeFromExtension(ext);
}

It works for some file, but not for some with more complicated characters in them, which I don't really understand, example below:

enter image description here

The files with tildas are all functional mp3s but all return null for their MIME types, which isn't good for functioning mp3s, so I'm curious if there's any simple workaround for files with special chars in their name.

Upvotes: 1

Views: 930

Answers (2)

Squonk
Squonk

Reputation: 48871

As it's the extension that you really need to work with getMimeTypeFromExtension(..), you could try getting it yourself by simply using lastIndexOf(".") to get the extension as a 'substring' from File.getAbsolutePath().

Upvotes: 2

Michele
Michele

Reputation: 6131

Its because of the "~" character in your filenames.

Look at the implementation of getFileExtensionFromUrl

/**
 * Returns the file extension or an empty string iff there is no
 * extension.
 */

public static String getFileExtensionFromUrl(String url) {
    if (url != null && url.length() > 0) {
        int query = url.lastIndexOf('?');
        if (query > 0) {
            url = url.substring(0, query);
        }
        int filenamePos = url.lastIndexOf('/');
        String filename =
            0 <= filenamePos ? url.substring(filenamePos + 1) : url;

    // if the filename contains special characters, we don't
    // consider it valid for our matching purposes:
    if (filename.length() > 0 &&
        Pattern.matches("[a-zA-Z_0-9\\.\\-\\(\\)]+", filename)) { // <--
        int dotPos = filename.lastIndexOf('.');
        if (0 <= dotPos) {
            return filename.substring(dotPos + 1);
        }
    }
}

return "";

}

a possible solution would be to write your own implemenation of this method with wider matching rule. Hope this helps

Upvotes: 4

Related Questions