Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to determine mime type of a file in java? [duplicate]

Tags:

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");   } 
like image 607
James Avatar asked Aug 26 '10 14:08

James


People also ask

How do I find the MIME type for a file?

To fetch mime type for a file, you would simply use Files and do this in your code: Files. probeContentType(Paths. get("either file name or full path goes here"));

How do I specify a MIME type?

A MIME type has two parts: a type and a subtype. They are separated by a slash (/). For example, the MIME type for Microsoft Word files is application and the subtype is msword. Together, the complete MIME type is application/msword.

Can a file have multiple MIME types?

Multiple MIME types can use one extension. For example, if your organization uses multiple versions of a program, you can define a MIME type for each version; however, file names of all versions use the same extension.

Can MIME type be faked?

MIME types also can not be misleading. MIME types are the authoritative declaration of what something is. If it's not that, then there is nothing misleading, it's simply invalid. Framing this as "MIME spoofing" is about as sensible as calling a buffer overflow in some font renderer "machine code spoofing".


1 Answers

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.

like image 140
BalusC Avatar answered Sep 27 '22 23:09

BalusC