您可以使用mime type
代替尝试通过文件扩展名来猜测,在某些情况下可能会丢失。以下是建立mime type
文件的选项:
使用javax.activation.MimetypesFileTypeMap
,例如:
System.out.println("Mime Type of " + f.getName() + " is " +
new MimetypesFileTypeMap().getContentType(f));
使用java.net.URL
URL u = new URL(fileUrl);
URLConnection uc = u.openConnection();
type = uc.getContentType();
使用Apache Tika
ContentHandler contenthandler = new BodyContentHandler();
Metadata metadata = new Metadata();
metadata.set(Metadata.RESOURCE_NAME_KEY, f.getName());
Parser parser = new AutoDetectParser();
// OOXMLParser parser = new OOXMLParser();
parser.parse(is, contenthandler, metadata);
System.out.println("Mime: " + metadata.get(Metadata.CONTENT_TYPE));
System.out.println("Title: " + metadata.get(Metadata.TITLE));
System.out.println("Author: " + metadata.get(Metadata.AUTHOR));
System.out.println("content: " + contenthandler.toString());
使用JMimeMagic
MagicMatch match = parser.getMagicMatch(f);
System.out.println(match.getMimeType()) ;
使用mime-util
Collection<?> mimeTypes = MimeUtil.getMimeTypes(f);
使用机器人
Droid (Digital Record Object Identification) is a software tool to
perform automated batch identification of file formats.
孔径框架
Aperture is an open source library and framework for crawling and indexing
information sources such as file systems, websites and mail boxes.
有关上述每个选项的更多详细信息,请参阅从文件中获取 Mime 类型。
在这种情况下,最简单的方法是使用第一个解决方案 javax.activation.MimetypesFileTypeMap
,例如:
MimetypesFileTypeMap mtft = new MimetypesFileTypeMap();
String mimeType = mtft.getContentType(ze.getName());
System.out.println(ze.getName()+" type: "+ mimeType);