Get the Mime Type from a FileTag(s): IO
Using Java 7
Files.html#probeContentTypeimport java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class Test { public static void main(String[] args) throws IOException { Path source = Paths.get("c:/temp/0multipage.tif"); System.out.println(Files.probeContentType(source)); // output : image/tiff } }
Using javax.activation.MimetypesFileTypeMap
activation.jar is required, it can be downloaded from http://java.sun.com/products/javabeans/glasgow/jaf.html.The MimetypesFileMap class is used to map a File to a Mime Type. Mime types supported are defined in a ressource file inside the activation.jar.
import javax.activation.MimetypesFileTypeMap; import java.io.File; class GetMimeType { public static void main(String args[]) { File f = new File("gumby.gif"); System.out.println("Mime Type of " + f.getName() + " is " + new MimetypesFileTypeMap().getContentType(f)); // expected output : // "Mime Type of gumby.gif is image/gif" } }
The MimetypesFileTypeMap looks in various places in the user's system for MIME types file entries. When requests are made to search for MIME types in the MimetypesFileTypeMap, it searches MIME types files in the following order:
- Programmatically added entries to the MimetypesFileTypeMap instance.
- The file .mime.types in the user's home directory.
- The file <java.home>/lib/mime.types.
- The file or resources named META-INF/mime.types.
- The file or resource named META-INF/mimetypes.default (usually found only in the activation.jar file).
Using java.net.URL
Warning : this method is very slow!.Like the above method a match is done with the extension. The mapping between the extension and the mime-type is defined in the file [jre_home]\lib\content-types.properties
import java.net.*; public class FileUtils{ public static String getMimeType(String fileUrl) throws java.io.IOException, MalformedURLException { String type = null; URL u = new URL(fileUrl); URLConnection uc = null; uc = u.openConnection(); type = uc.getContentType(); return type; } public static void main(String args[]) throws Exception { System.out.println(FileUtils.getMimeType("file://c:/temp/test.TXT")); // output : text/plain } }
I was trying to find the best way of getting the mime type of a file and found your sight very useful. However I have now found a way of getting the mime type using URLConnection that isn't as slow as the way you describe.
import java.net.FileNameMap; import java.net.URLConnection; public class FileUtils { public static String getMimeType(String fileUrl) throws java.io.IOException { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String type = fileNameMap.getContentTypeFor(fileUrl); return type; } public static void main(String args[]) throws Exception { System.out.println(FileUtils.getMimeType("file://c:/temp/test.TXT")); // output : text/plain } }
Using Apache Tika
Tika is subproject of Lucene, a search engine. It is a toolkit for detecting and extracting metadata and structured text content from various documents using existing parser libraries.This package is very up-to-date regarding the filetypes supported, Office 2007 formats are supported (docs/pptx/xlsx/etc...).
Tika has a lot of dependencies ... almost 20 jars ! But it can do a lot more than detecting filetype. For example, you can parse a PDF or DOC to extract the text and the metadata very easily.
import java.io.File; import java.io.FileInputStream; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.parser.Parser; import org.apache.tika.sax.BodyContentHandler; import org.xml.sax.ContentHandler; public class Main { public static void main(String args[]) throws Exception { FileInputStream is = null; try { File f = new File("C:/Temp/mime/test.docx"); is = new FileInputStream(f); ContentHandler contenthandler = new BodyContentHandler(); Metadata metadata = new Metadata(); metadata.set(Metadata.RESOURCE_NAME_KEY, f.getName()); Parser parser = new AutoDetectParser(); // OOXMLParser parser = new OOXMLParser(); parser.parse(is, contenthandler, metadata); System.out.println("Mime: " + metadata.get(Metadata.CONTENT_TYPE)); System.out.println("Title: " + metadata.get(Metadata.TITLE)); System.out.println("Author: " + metadata.get(Metadata.AUTHOR)); System.out.println("content: " + contenthandler.toString()); } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) is.close(); } } }
Using JMimeMagic
Checking the file extension is not a very strong way to determine the file type. A more robust solution is possible with the JMimeMagic library. JMimeMagic is a Java library (LGLP licence) that retrieves file and stream mime types by checking magic headers.// snippet for JMimeMagic lib // http://sourceforge.net/projects/jmimemagic/ Magic parser = new Magic() ; // getMagicMatch accepts Files or byte[], // which is nice if you want to test streams MagicMatch match = parser.getMagicMatch(new File("gumby.gif")); System.out.println(match.getMimeType()) ;
Using mime-util
Another tool is mime-util. This tool can detect using the file extension or the magic header technique.import eu.medsea.mimeutil.MimeUtil; public class Main { public static void main(String[] args) { MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector"); File f = new File ("c:/temp/mime/test.doc"); Collection<?> mimeTypes = MimeUtil.getMimeTypes(f); System.out.println(mimeTypes); // output : application/msword } }
Send comment, question or suggestion to howto@rgagnon.com