Reputation: 10158
i get mime type of a file using the following code:
private String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
Log.e("extension ", extension);
if (extension != null) {
MimeTypeMap mime = MimeTypeMap.getSingleton();
type = mime.getMimeTypeFromExtension(extension);
}
return type;
}
where url is the absolute file path
i am getting file and folder by the following way
File file_arr [];
file_arr = new File(Environment.getExternalStorageDirectory().getPath()).listFiles();
url = file_arr[i].getAbsolutePath();
this is working correct but it return always null for which file has dot " . " in its file name.
for the example
if the file name is picture1.jpg then the getMimeType() return image/jpeg
in the case of file name has dot (.) in its name for the example 27-05-2012 22.05.14.jpg then the getMimeType() return null.
i have renamed the file to 27-05-2012.jpg, its return image/jpeg.
my question how to get mime type for all types of file name(which is has dot or special character) on android? please help me.
Upvotes: 1
Views: 9797
Reputation: 5817
How about this:
File f = new File(file);
System.out.println(new MimetypesFileTypeMap().getContentType(f));
Or
if (url.lastIndexOf(".") != -1) {
String ext = url.substring(url.lastIndexOf(".") + 1);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String type = mime.getMimeTypeFromExtension(ext);
} else {
String type = null;
}
Upvotes: 13
Reputation: 11107
private String getMimeType(String url) {
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(url);
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
fileExtension);
Toast.makeText(
this,
"FileExtension: " + fileExtension + "\n" + "MimeType: "
+ mimeType, Toast.LENGTH_LONG).show();
return mimeType;
}
Problem is with space in between your file name , try this code for getting mime type for any file that is having ( "." , "-" , "_" )etc...
Try with this even it will work : 27-05-20.....1222.05.14.jpg
Upvotes: 1