As far as I'm aware there's only three ways to get the MIME type from reading the existing questions.
1) Determining it from the file extension using MimeTypeMap.getFileExtensionFromUrl
2) "Guess" using the inputStream
with URLConnection.guessContentTypeFromStream
3) Using the ContentResolver
to get the MIME type using content Uri (content:\) context.getContentResolver().getType
However, I only have the file object, with the obtainable Uri
being the file path Uri
(file:). The file does not have an extension. Is there still a way to get the MIME type of the file? Or a way to determine the content Uri from the file path Uri?
Have you tried this? It works for me (only for image files).
public static String getMimeTypeOfUri(Context context, Uri uri) {
BitmapFactory.Options opt = new BitmapFactory.Options();
/* The doc says that if inJustDecodeBounds set to true, the decoder
* will return null (no bitmap), but the out... fields will still be
* set, allowing the caller to query the bitmap without having to
* allocate the memory for its pixels. */
opt.inJustDecodeBounds = true;
InputStream istream = context.getContentResolver().openInputStream(uri);
BitmapFactory.decodeStream(istream, null, opt);
istream.close();
return opt.outMimeType;
}
Of course you can also use other methods, such as BitmapFactory.decodeFile
or BitmapFactory.decodeResource
like this:
public static String getMimeTypeOfFile(String pathName) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pathName, opt);
return opt.outMimeType;
}
It will return null if failed to determine the MIME type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With