androidmime-typesfilenamesandroid-file

how to get mime type of a file,which has dot in the file name on android


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.


Solution

  • 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;
    }