How to get MIME Type of a file in Java

Below examples, shows different ways of getting the the MimeType for a given file using the standard Java

Method 1 : Using FileNameMap

import java.net.FileNameMap;
import java.net.URLConnection;
            
	public String getMimeType(String fileName) throws Exception {		
		FileNameMap fileNameMap = URLConnection.getFileNameMap();
		String mimeType = fileNameMap.getContentTypeFor(fileName);
		return mimeType
	}

Method 2 : Using Files.probeContentType()

import java.io.File;
import java.nio.file.Files;

	public String getMimeType(String fileName) throws Exception {		
		String mimeType = Files.probeContentType(new File(file).toPath());
		return mimeType
	}

Method 3 : Using URLConnection.guessContentTypeFromName()

import java.net.URLConnection;

	public String getMimeType(String fileName) throws Exception {		
		String mimeType = URLConnection.guessContentTypeFromName(fileName);
		return mimeType
	}