我正在使用 Apache Tika,并且我有特定内容类型的文件(没有扩展名)需要重命名以具有反射(reflect)内容类型的扩展名。
知道是否有什么我可以使用而不是根据内容类型名称从头开始编程的东西吗?
最佳答案
你的两个关键类是MediaTypeRegistry和 MimeTypes .使用这些,您可以进行基于 mime 类型魔术的检测,并获取有关 mime 类型及其关系的信息。
(也就是说,如果您想进行全面检测,可能涉及使用 Tika Parsers jar 中针对基于容器的格式的额外逻辑对文件进行一些解析,您应该使用 TikaConfig.getDetector() 和/或 DefaultDetector .)
// Load your Tika config, find all the Tika classes etc
TikaConfig config = TikaConfig.getDefaultConfig();
// Do the detection. Use DefaultDetector / getDetector() for more advanced detection
Metadata metadata = new Metadata();
InputStream stream = TikaInputStream.get(new File(file), metadata);
MediaType mediaType = config.getMimeRepository().detect(stream);
// Fest the most common extension for the detected type
MimeType mimeType = config.getMimeRepository().forName(mediaType.toString());
String extension = mimeType.getExtension();
关于java - 如何从内容类型中获取文件扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5541694/