title: Identify File Type in Java
body: <p>I want to check that the user uploads only a particular file format (say text files only).</p>
  
  <p>I've written a verification mechanism which checks for format after the file name like this</p>
  
  <pre><code>filename.txt
  </code></pre>
  
  <p>But, this created a problem when it was accepting other files also (like excel files) which are saved as .txt like</p>
  
  <pre><code>myexcelfile.txt is being assumed as a text file even when it is an excel file
  </code></pre>
  
  <p>So, What would be the unique parameter to check for to make sure that the uploaded file is of the required type?</p>
  
  <p>Using apache-commons uploader, servlets.</p>
  
  <p>======================EDIT=====================</p>
  
  <p>Based on answers below, I've tried</p>
  
  <pre><code>FileInputStream my = new FileInputStream(uploadedFile2);
  InputStream inputStream = new BufferedInputStream(my);
  String mimeType = URLConnection.guessContentTypeFromStream(inputStream);
  </code></pre>
  
  <p>But is always returning a null value.</p>
  
  <p><a href="http://docs.oracle.com/javase/8/docs/api/java/nio/file/spi/FileTypeDetector.html" rel="nofollow noreferrer">probe content type</a> is based on filename extension and also there is a bug with <a href="https://stackoverflow.com/questions/12407479/why-does-files-probecontenttype-return-null.">this approach</a>, checked that too. </p>
  
  <p>I don't prefer to use third party file verifiers, I believe that this problem will have a logical solution.</p>