Get the Mime Type from a File
I recently had to find the type of a file. I relied only on file extension, which as you can see, is unreliable. The following method is preferred:
Using javax.activation.MimetypesFileTypeMap
import javax.activation.MimetypesFileTypeMap;
import java.io.File;
class GetMimeType {
public static void main(String args[]) {
File f = new File("gumby.gif");
System.out.println("Mime Type of " + f.getName() + " is " +
new MimetypesFileTypeMap().getContentType(f));
// expected output :
// "Mime Type of gumby.gif is image/gif"
}
}
The built-in mime-type list is very limited but a mechanism is available to add very easily more Mime Types/extensions.The MimetypesFileTypeMap looks in various places in the user's system for MIME types file entries. When requests are made to search for MIME types in the MimetypesFileTypeMap, it searches MIME types files in the following order:
- Programmatically added entries to the MimetypesFileTypeMap instance.
- The file .mime.types in the user's home directory.
- The file
/lib/mime.types.
- The file or resources named META-INF/mime.types.
- The file or resource named META-INF/mimetypes.default (usually found only in the activation.jar file).
This method is interesting when you need to deal with incoming files with the filenames normalized. The result is very fast because only the extension is used to guess the nature of a given file.
For a file read via URL, use the following method:
import java.net.FileNameMap;
import java.net.URLConnection;
public class FileUtils {
public static String getMimeType(String fileUrl)
throws java.io.IOException
{
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String type = fileNameMap.getContentTypeFor(fileUrl);
return type;
}
public static void main(String args[]) throws Exception {
System.out.println(FileUtils.getMimeType("file://c:/temp/test.TXT"));
// output : text/plain
}
}
0 komentar:
Posting Komentar