Friday, July 28, 2017

Reading File MIME Type

  What I'm about to share with you covers basic MIME type reading. In some cases, you don't want to use additional external libraries for your project. For this simple task, using readily available classes on Java is always a joy.

  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:

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:

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
view raw Main.java hosted with ❤ by GitHub

What else you need to know?

The list of supported MIME types are located on your JRE. Locate the file named content-types.properties at <JRE>/lib directory.  This file is being read by sun.net.www.MimeTable class which happens to be an implementation of java.net.FileNameMap. And, the default instance returned by URLConnection.getFileNameMap() function.

1 comment:

  1. I never thought MIME types are existing in the JRE dir! GREAT UTILITY

    ReplyDelete

Starting with Basic File Cryptography (XOR Cipher)

  In this blog post, I'll discuss one interesting basic cipher technique to garble a file: The "XOR Cipher". What it does is o...