21

Curious what the best way is in Java to get the mime-type of a file. It should actually inspect the file because filenames aren't an accurate indicator.

Currently I'm using the following which seems to be very hit or miss

  is = new BufferedInputStream(new FileInputStream(fileName));
  String mimeType = URLConnection.guessContentTypeFromStream(is);
  if(mimeType == null) {
    throw new IOException("can't get mime type of image");
  }
James
  • 15,085
  • 25
  • 83
  • 120

3 Answers3

26

The URLConnection#guessContentTypeFromStream() or ...FromName() is indeed the best what you can get in the standard Java SE API. There are however 3rd party libraries like jMimeMagic which does its work better than URLConnection#guessXXX() methods.

String mimeType = Magic.getMagicMatch(file, false).getMimeType();

This supports a more wide range of mime types.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • @BalusC What can you say about this SO question [check file of MIME-type with JMimeMagic](http://stackoverflow.com/questions/15325047/check-file-of-mime-type-with-jmimemagic)? – catch23 Mar 11 '13 at 15:12
  • @BalusC i tried to use it but with docx files it returns that the mime type is application/zip which is not correct – Mahmoud Saleh Feb 22 '16 at 12:01
6

Following link has a good comparison of various ways of getting the Mime type of a file (it includes libraries like: Apache Tika, JMimeMagic etc. with some native code too): http://www.rgagnon.com/javadetails/java-0487.html

vikasing
  • 11,562
  • 3
  • 25
  • 25
0
    public static String getContentType(String filename)
    {
        String g = URLConnection.guessContentTypeFromName(filename);
        if( g == null)
        {
            g = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(filename);
        }
        return g;
    }
Ray Hulha
  • 10,701
  • 5
  • 53
  • 53