zoukankan      html  css  js  c++  java
  • android: android中根据文件的mime type 获取后缀名的方法

    看了很多文章,都是用一个HashMap去做的,比如建立一个HashMap, key 是“audio/mp3”, value 就是"mp3", 然后创建大量mime type与 file format 对应的键值对,今天找到一个简单的办法:

    先拿到文件的mimeType:

    MediaMetadataRetriever mMediaMetadataRetriever = new MediaMetadataRetriever();
    mMediaMetadataRetriever.setDataSource(getApplicationContext(), audioFileUri);
    
    
    String mimeType = mMediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
    String fileExtension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);

    PS:

    1.  MediaMetadataRetriever 可用来获取媒体文件的详细信息,如:视频的时长,音频采样率,声道数等,操作媒体文件很好用,其它类型的文件没试过,用它可以快速得到文件的mime type; 

    2. 利用 MimeTypeMap 这个类快速得到文件的后缀名。不仅如此,它还可以通过url 快速得到文件的后缀名,通过后缀名快速得到mime type:

    // url = file path or whatever suitable URL you want.
    public static String getMimeType(String url) {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);
        if (extension != null) {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        }
        return type;
    }

    参考:How to determine MIME type of file in android?

  • 相关阅读:
    rest_framework学习之路
    jQuery操作cookie
    Cookie和Session
    HTTP之Content-Type
    HTTP协议
    Python之random模块
    HTML5(FileRdeader)
    Python之re模块
    LINQ基础 之 LINQ TO SQL (二)
    LINQ基础(一)
  • 原文地址:https://www.cnblogs.com/yongdaimi/p/13645719.html
Copyright © 2011-2022 走看看