Take extra care because not all commonly known MIME types are supported. I will show you that on the last part. Let's start.
The code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package blog.boydeploy.mimetype; | |
import java.io.File; | |
import java.io.FileNotFoundException; | |
import java.net.FileNameMap; | |
import java.net.URLConnection; | |
import java.util.Objects; | |
public class MimeUtility { | |
public static String getMimeType(File file) throws FileNotFoundException { | |
Objects.requireNonNull(file); | |
if (!file.exists()) throw new FileNotFoundException("File is missing: " + file.getAbsolutePath()); | |
FileNameMap fmap = URLConnection.getFileNameMap(); | |
return fmap.getContentTypeFor(file.toURI().getPath()); | |
} | |
} |
Some Test:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package blog.boydeploy.mimetype; | |
import java.io.File; | |
import java.io.FileNotFoundException; | |
public class Main { | |
public static void main(String... args) throws Exception { | |
printMIME(new File("D:\\CS-KEYBOARD SHORTCUTS.pdf")); | |
printMIME(new File("D:\\1.jpg")); | |
} | |
private static void printMIME(File f) throws FileNotFoundException { | |
System.out.println("file = " + f.getAbsolutePath()); | |
System.out.println("mime = " + MimeUtility.getMimeType(f)); | |
} | |
} | |
Output: | |
file = D:\CS-KEYBOARD SHORTCUTS.pdf | |
mime = application/pdf | |
file = D:\1.jpg | |
mime = image/jpeg | |
I never thought MIME types are existing in the JRE dir! GREAT UTILITY
ReplyDelete