Programming Tips - Java: Get the mime type of a file by reading the bytes

Date: 2016jun23 Language: Java Keywords: magic Q. Java: 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 guessMimeType(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.