Suppose I have a full path of file like:(/sdcard/tlogo.png). I want to know its mime type.
I created a function for it
public static String getMimeType(File file, Context context)
{
Uri uri = Uri.fromFile(file);
ContentResolver cR = context.getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
String type = mime.getExtensionFromMimeType(cR.getType(uri));
return type;
}
but when i call it, it returns null.
File file = new File(filePath);
String fileType=CommonFunctions.getMimeType(file, context);
Optimized version of Jens' answere with null-safety and fallback-type.
Update (19.03.2018)
Bonus: Above methods as a less verbose Kotlin extension function:
Sometimes Jeb's and Jens's answers don't work and return null. In this case I use follow solution. Head of file usually contains type signature. I read it and compare with known in list of signatures.
signatureId
is an index of signature in array of signatures. For example,Now I have file type even if URI of file haven't. Next I get mime type by file type. If you don't know which mime type to get, you can find proper in this table.
It works for a lot of file types. But for video it doesn't work, because you need to known video codec to get a mime type. To get video's mime type I use MediaMetadataRetriever.
The above solution returned null in case of .rar file, using URLConnection.guessContentTypeFromName(url) worked in this case.
Has also return null value in my case path was
as work around use
so method looks like
as result it return success result:
Hope it helps anybody