且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正确使用 Apache Tika MediaType

更新时间:2023-02-17 11:27:44

您需要做的是遍历类型层次结构,直到找到您想要的内容,或者用完要检查的内容.这可以用递归来完成,也可以用循环来完成

What you'll need to do is walk the types hierarchy, until you either find what you want, or run out of things to check. That can be done with recursion, or could be done with a loop

您需要的关键方法是MediaTypeRegistry.getSupertype(MediaType)

你的代码应该是这样的:

Your code would want to be something like:

// Define your media type constants here
MediaType FOO = MediaType.parse("application/foo");

// Work out the file's type
MediaType type = detector.detect(stream, metadata);

// Is it one we want in the tree?
while (type != null && !type.equals(MediaType.OCTET_STREAM)) {
   if (type.equals(MediaType.Application_XML)) {
       doThingForXML();
   } else if (type.equals(MediaType.APPLICATION_ZIP)) { 
       doThingForZip();
   } else if (type.equals(FOO)) {
       doThingForFoo();
   } else {
       // Check parent
       type = registry.getSuperType(type);
   }
}