Home » Tip Bank » Java
  • Comment on this Article
Language: Java
Expertise: Intermediate
Jul 5, 2019
  • facebook
  • twitter
  • in
  • Email

WEBINAR:

On-Demand

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


Watch

Finding the Mime Type of a File

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

*/
M S Sridhar
 
Submit a Tip
Browse "Java" Tips
Browse All Tips
w3schools.com
codeschool.com