dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tip: Finding the Mime Type of a File

Learn how to find the MIME type of a file in Java.


advertisement

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


Finding the MIME type of a file is useful when you want to perform certain actions.

PS: I have placed a file named nature.jpg in the folder /home/sridhar before executing this class.

Code sample:

import java.nio.file.*;
import java.io.*;

public class FindMIMEType
{
   public static void main(String args[])
   {
      FindMIMEType findMIMEType = new FindMIMEType();
      findMIMEType.proceed();
   }
   
   private void proceed()
   {
      Path filename = Paths.get("/home/sridhar/nature.jpg");
      
      try 
      {
         //This method probeContentType returns the content type of the file being considered
         String mimeType = Files.probeContentType(filename);
         System.out.println("MIME type of " + filename + " is " + mimeType);
      } 
      catch (IOException ioe) 
      {
         System.out.println(ioe);
      }      
   }   
}

/*

Expected output:

[root@mypc]# java FindMIMEType
MIME type of /home/sridhar/nature.jpg is image/jpeg

*/

 

Visit the DevX Tip Bank

 





   
Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Thanks for your registration, follow us on our social networks to keep up-to-date