Dave's Brain

Browse - Programming Tips - How can I get the mime type of a file by reading the bytes?

Date: 2016jun23
Language: Java

Q.  How can I get the mime type of a file by reading the bytes?
Not looking at the extension.
I don't want to include an extra library.
Like the Linux "file" command.

A.  URLConnection has a member for this.

import java.io.IOException; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.net.URLConnection; String guessMime(String filename) { String mimeType = ""; try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filename)); mimeType = URLConnection.guessContentTypeFromStream(bis); bis.close(); } catch (IOException ex) { // Do something with exception } return mimeType; }
Will return "image/jpeg", "image/png", etc.

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.