Apache Tika: Mime type detection of a file
<p>Is it possible to extract metadata and detect mime type from single file read? This is working for most of the files.</p>

<pre><code>  TikaInputStream tikaStream = null;  
  File file = new File(args[0]);
  FileInputStream stream = new FileInputStream(file);
  tikaStream = TikaInputStream.get(stream);

  Parser parser = new AutoDetectParser();

  //The content is parsed as SAX XHTML events
  BodyContentHandler handler = new BodyContentHandler();

  //File meta data is set in this object 
  Metadata metadata = new Metadata();

  //To provide custom inputs if specific parser is chosen
  ParseContext context = new ParseContext();
  parser.parse(tikaStream, handler, metadata, context);

  String[] metadataNames = metadata.names();
  for(String name : metadataNames) {
     System.out.println(name + "::" + metadata.get(name));
  }

  Tika tika = new Tika();
  String filetype = tika.detect(tikaStream, metadata); 
</code></pre>

<p>I do get the following exception for few formats</p>

<pre><code>org.apache.tika.io.TaggedIOException: Stream closed
    at org.apache.tika.io.TaggedInputStream.handleIOException(TaggedInputStream.java:133)
    at org.apache.tika.io.ProxyInputStream.reset(ProxyInputStream.java:170)
    at org.apache.tika.io.TikaInputStream.reset(TikaInputStream.java:674)
    at org.apache.tika.parser.microsoft.POIFSContainerDetector.detect(POIFSContainerDetector.java:436)
    at org.apache.tika.detect.CompositeDetector.detect(CompositeDetector.java:77)
    at org.apache.tika.Tika.detect(Tika.java:156)
    at DocumentTypeDetection.main(DocumentTypeDetection.java:55)
Caused by: java.io.IOException: Stream closed
    at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:162)
    at java.io.BufferedInputStream.reset(BufferedInputStream.java:435)
    at org.apache.tika.io.ProxyInputStream.reset(ProxyInputStream.java:168)
</code></pre>