Friday, July 05, 2013

How to read a file MIME Type in Java

There is an extension in a file name which says it is an .xls extension. But you can rename an .txt file also to .xls file. So just by reading extension if you want to find the file type, then below are the methods

Method 1
String g = URLConnection.guessContentTypeFromName(filename);
         if( g == null)
         {
             g = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(filename);
         }


Method 2
FileNameMap fileNameMap = URLConnection.getFileNameMap();
       String type = fileNameMap.getContentTypeFor("file://" + filename);
       System.out.println(filename + "-"+type);


Method 3
 This is available in Jre 7
try
   {
    Path p = Paths.get(filename);
    s = Files.probeContentType(p);
    System.out.println("Mime type" + s);
   }
   catch(IOException e)
   {

   }


Method 4
File obFile = new File(filename);
String mimeType= URLConnection.guessContentTypeFromName(obFile.getName());
System.out.println(filename + "-"+mimeType);

If you want to read the file and then find the MIME Type

Method 5
  This is using Apache Tikia  which identifies the filetype using magic byte patterns and globbing hints (the file extension) to detect the MIME type.

 File file = new File(filename);
         AutoDetectParser parser = new AutoDetectParser();
         parser.setParsers(new HashMap<MediaType, Parser>());

         Metadata metadata = new Metadata();
         metadata.add(TikaMetadataKeys.RESOURCE_NAME_KEY, file.getName());

         InputStream stream;
   try
   {
    stream = new FileInputStream(file);
    parser.parse(stream, new DefaultHandler(), metadata, new ParseContext());
       stream.close();
   }
   catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (SAXException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (TikaException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
    String mimeType = metadata.get(HttpHeaders.CONTENT_TYPE);
       System.out.println(mimeType);

No comments: