Getting A File's Mime Type In Java

后端 未结 23 2762
南方客
南方客 2020-11-21 06:53

I was just wondering how most people fetch a mime type from a file in Java? So far I\'ve tried two utils: JMimeMagic & Mime-Util.

Th

23条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 07:21

    Unfortunately,

    mimeType = file.toURL().openConnection().getContentType();
    

    does not work, since this use of URL leaves a file locked, so that, for example, it is undeletable.

    However, you have this:

    mimeType= URLConnection.guessContentTypeFromName(file.getName());
    

    and also the following, which has the advantage of going beyond mere use of file extension, and takes a peek at content

    InputStream is = new BufferedInputStream(new FileInputStream(file));
    mimeType = URLConnection.guessContentTypeFromStream(is);
     //...close stream
    

    However, as suggested by the comment above, the built-in table of mime-types is quite limited, not including, for example, MSWord and PDF. So, if you want to generalize, you'll need to go beyond the built-in libraries, using, e.g., Mime-Util (which is a great library, using both file extension and content).

提交回复
热议问题