作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
这是我阅读 mime 类型的类(class)。我正在尝试添加一个新的 mime 类型(属性文件)并阅读它。
这是我的类文件:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package check_mime;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.tika.Tika;
import org.apache.tika.mime.MimeTypes;
public class TikaFileTypeDetector {
private final Tika tika = new Tika();
public TikaFileTypeDetector() {
super();
}
public String probeContentType(Path path) throws IOException {
// Check contents first
String fileContentDetect = tika.detect(path.toFile());
if (!fileContentDetect.equals(MimeTypes.OCTET_STREAM)) {
return fileContentDetect;
}
// Try file name only if content search was not successful
String fileNameDetect = tika.detect(path.toString());
if (!fileNameDetect.equals(MimeTypes.OCTET_STREAM)) {
return fileNameDetect;
}
return null;
}
public static void main(String[] args) throws IOException {
Tika tika = new Tika();
if (args.length != 1) {
printUsage();
return;
}
Path path = Paths.get(args[0]);
TikaFileTypeDetector detector = new TikaFileTypeDetector();
String contentType = detector.probeContentType(path);
System.out.println("File is of type - " + contentType);
}
public static void printUsage() {
System.out.print("Usage: java -classpath ... "
+ TikaFileTypeDetector.class.getName()
+ " ");
}
}
来自docs我创建了一个自定义 xml:
<?xml version="1.0" encoding="UTF-8"?>
<mime-info>
<mime-type type="text/properties">
<glob pattern="*.properties"/>
</mime-type>
</mime-info>
现在我该如何添加到我的程序中并读取它。我必须创建一个解析器吗?我被困在这里。
最佳答案
这包含在 Apache Tika 5 minute parser instructions 中.要添加对 Java .properties 文件的支持,您应该首先创建一个名为 custom-mimetypes.xml
的文件,并在其中填充如下内容:
<?xml version="1.0" encoding="UTF-8"?>
<mime-info>
<mime-type type="text/properties">
<_comment>Java Properties</_comment>
<glob pattern="*.properties"/>
<sub-class-of type="text/plain"/>
</mime-type>
</mime-info>
接下来,您需要将它放在 Tika 可以找到的地方,并使用正确的名称。它必须作为 org/apache/tika/mime/custom-mimetypes.xml
存储在您的类路径中。最简单的做法是创建该目录结构,将新文件移入,然后将根目录添加到您的类路径中。对于部署,您应该将其打包到一个 jar 中并将其放在类路径中
如果您小心的话,您可以使用 Tika 应用程序来检查您的 mime 类型文件是否已加载。将您的代码打包为 jar,然后像这样运行它:
java -classpath tika-app-1.10-SNAPSHOT.jar:my-custom-mimetypes.jar org.apache.tika.cli.TikaCLI --list-supported-types | grep text/properties
或者,如果您在本地目录中有它,请尝试类似的操作
ls -l org/apache/tika/mime/custom-mimetypes.xml
# Check a file was found, with some content in it
java -classpath tika-app-1.10-SNAPSHOT.jar:. org.apache.tika.cli.TikaCLI --list-supported-types | grep text/properties
如果那没有显示您的 MIME 类型,那么您没有得到正确的路径或文件名,请仔细检查它们
(或者,升级到更新版本的 Apache Tika,因为 r1686315 Tika 内置了 Java Properties mimetype!)
关于java - 如何向 apache tika 添加新的 mime 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30895761/
我是一名优秀的程序员,十分优秀!