get Mime Type for a file path - Android File Input Output

Android examples for File Input Output:File Name

Description

get Mime Type for a file path

Demo Code


//package com.book2s;

import android.text.TextUtils;
import android.webkit.MimeTypeMap;

public class Main {
    public static String getMimeType(String filePath) {
        String type = null;//from w  w w . j ava 2 s  .c  o m
        String extension = getSuffix(filePath);
        if (!TextUtils.isEmpty(extension)) {
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            type = mime.getMimeTypeFromExtension(extension);
        }
        if (TextUtils.isEmpty(type)) {
            type = "file/*";
        }
        return type;
    }

    public static String getSuffix(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return null;
        }
        int dotPos = filePath.lastIndexOf('.');
        if (dotPos >= 0 && dotPos < filePath.length() - 1) {
            return filePath.substring(dotPos + 1);
        }
        return null;
    }
}

Related Tutorials