Getting file types using Java __java

Source: Internet
Author: User
Using Java 7Files.html#probecontenttype

Import 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/0 Multipage.tif ");
    System.out.println (source) (Files.probecontenttype);
    Output:image/tiff
  }
}
The default implementation is os-specific and not very complete. It ' s possible to register a better detector, like for example Apache Tika, and the transparently improve Java 7 Mime-type Rec Ognition with Apache Tika. Using Javax.activation.MimetypesFileTypeMapActivation.jar is required, the 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 built-in Mime-type list is very limited but a mechanism are available to add very easily more mime types/extensions.

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). This are interesting when you need to deal with incoming files with the filenames normalized. The result is very fast because only the extension was used to guess the nature of a given file. Using Java.net.URL Warning:this method is  very slow!.

Like the above method a match being 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{
  the 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
  }
}
A note from R. Lovelock:
I was trying to find the best way of getting the MIME type of a file and
found your sight very. However I have now found a way of
getting the MIME type using urlconnection that isn ' t as slow as the
way for you desc Ribe.
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 TikaTika is subproject of Lucene, a search engine. It is a toolkit to detecting and extracting metadata and structured text content from various documents using Existin G Parser Libraries.

This package is very up-to-date regarding the filetypes supported, Office 2007 formats (are) supported docs/pptx/xlsx/etc. .).

Apache Tika

Tika has a lot of dependencies ... almost jars! But It can do a lot more than detecting filetype. For example, 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 ();
 }
  }
}
Can download here a ZIP containing the required jars if you want to check it out. Using jmimemagicChecking The file extension is isn't a very strong way to determine the file type. A more robust solution are possible with the Jmimemagic library. Jmimemagic is a Java library (LGLP licence), retrieves file and stream mime types by checking magic.
Snippet for jmimemagic Lib
//     http://sourceforge.net/projects/jmimemagic/

Magic parser = new Magic (); c4/>//Getmagicmatch accepts Files or byte[],
//which is nice if you want to test streams
magicmatch match = Pars Er.getmagicmatch (New File ("Gumby.gif"));
System.out.println (Match.getmimetype ());
Jean-marc Autexier and Sygsix for the tip! Using Mime-utilAnother 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
    }
}
The nice thing about mime-util are that it's very lightweight. Only 1 dependency with slf4j Using DroidThe DROID (Digital record Object identification) are a software tool to perform automated batch of the file identification.

The DROID uses internal and external signatures to identify and the specific file format versions of digital files. These signatures are stored in a XML signature file, generated from information recorded in the PRONOM technical . New and updated signatures are regularly added to Pronom, and DROID can being configured to automatically download Si Gnature files from the Pronom website via Web services.

It can be invoked from two interfaces, a Java Swing GUI or a command line interface.

Http://droid.sourceforge.net/wiki/index.php/Introduction Aperture Framework Aperture is a open source The library and framework for crawling and indexing information sources such as file systems, websites and mail boxes.

The Aperture code consists of a number of related but independently usable parts:crawling of information Sources:file Sy Stems, websites, mail boxes MIME type identification Full-text and metadata extraction of various file formats Opening of Crawled resources for each of the parts, a set of APIs has been developed and a number of implementations is provided.

Http://aperture.wiki.sourceforge.net/Overview

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.