2013-09-06 26 views
9

私が知っている限り、MIMEタイプを既存の質問から読み取る方法は3つしかありません。使用したファイルの拡張子からそれを決定Android - 拡張子のないファイルからMIMEタイプを取得

1)MimeTypeMap.getFileExtensionFromUrl

2)を使用して、 "ゲス" inputStreamContentResolverはコンテンツウリ(コンテンツを使用してMIMEタイプを取得するために使用しURLConnection.guessContentTypeFromStream

3)と:\) context.getContentResolver().getType

はしかし、私は唯一の入手Uriは、ファイルパスUri(ファイル:)ことで、ファイルオブジェクトを持っています。ファイルには拡張子がありません。まだファイルのMIMEタイプを取得する方法はありますか?または、ファイルパスUriからコンテンツUriを決定する方法?

+0

http://stackoverflow.com/a/30765320/2765497 – Flinbor

答えて

2

まだファイルのMIMEタイプを取得する方法はありますか?

ファイル名だけではありません。

また、ファイルパスUriからコンテンツUriを判断する方法はありますか?

「コンテンツUri」は必ずしもありません。あなたはMediaStoreでファイルを探して何らかの理由でMIMEタイプを知っているかどうかを調べることを歓迎します。 MediaStoreはMIMEタイプを知っていてもいなくてもよく、そうでなければそれを判断する方法はありません。

あなたはを行う場合はMIMEタイプを取得するためにContentResolvergetType()を使用し、content://Uriを持っています。

10

これを試しましたか?それは私のために働く(画像ファイルのためにのみ)。 MIMEタイプを決定するために失敗した場合にはnullを返します

public static String getMimeTypeOfFile(String pathName) { 
    BitmapFactory.Options opt = new BitmapFactory.Options(); 
    opt.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(pathName, opt); 
    return opt.outMimeType; 
} 

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

もちろん、あなたはまた、他の方法で、このようなようなBitmapFactory.decodeFileBitmapFactory.decodeResourceを使用することができます。

+1

が含まれている 'BitmapFactory'はいえ、画像ファイルのMIMEタイプを決定します。 –

+0

はい、もちろん、私はその説明を追加するのを忘れました:)ありがとう – BornToCode

1

まずバイトがファイルの拡張子

@Nullable 
public static String getFileExtFromBytes(File f) { 
    FileInputStream fis = null; 
    try { 
     fis = new FileInputStream(f); 
     byte[] buf = new byte[5]; //max ext size + 1 
     fis.read(buf, 0, buf.length); 
     StringBuilder builder = new StringBuilder(buf.length); 
     for (int i=1;i<buf.length && buf[i] != '\r' && buf[i] != '\n';i++) { 
      builder.append((char)buf[i]); 
     } 
     return builder.toString().toLowerCase(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      if (fis != null) { 
       fis.close(); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return null; 
} 
関連する問題