<p>How do you get a Media Type (MIME type) from a file using Java?  So far I've tried JMimeMagic &amp; Mime-Util. The first gave me memory exceptions, the second doesn't close its streams properly.</p>
<p>How would you probe the file to determine its actual type (not merely based on the extension)?</p>

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).