Determine the mime (content) type of a file

From CodeCodex

Implementations[edit]

Java[edit]

The code below requires a javax package that may not be present with your version of java. The javax.activation package is available for download here.

import javax.activation.MimetypesFileTypeMap;
Java.io.File file = ...
String fileType = new MimetypesFileTypeMap().getContentType( file );
System.out.println( "File " + file + " is of type " + fileType );

Note that MIME types are metadata, and cannot in general be reliably determined from the file contents or file name. Instead, they need to be explicitly specified and stored.

To see why, consider a file with the following contents. Should its MIME type be text/plain or text/html?

<html>
<head>
<title>a tricky example</title>
</head>
<body>
Hi There.
</body>
</html>

Yes, its content is syntactically HTML. If I wanted the recipient to view it as a Web page, then its MIME type should be text/html. But if I want the recipient to view it as an example HTML snippet, then it should be text/plain. Thus, the MIME type is part of the semantics of how the data is to be interpreted, which cannot be determined from the file name or file contents alone.

Python[edit]

<HIGHLIGHTSYNTAX language="python"> import mimetypes ftype, encoding = mimetypes.guess_type('/path/to/file.tar.gz') </HIGHLIGHTSYNTAX>