Java 返回 YAML 文件的 MIME 类型为 null。

3

Java 8 Files.probeContentType(new File("config.yml").toPath()); 返回 null。为什么 Java 找不到 YAML 的 MIME 类型,但可以找到 XML 的 text/xml?是否有其他方法?

foo: bar

2
因为 YAML 可能不会被默认支持。https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/nio/file/Files.html#probeContentType(java.nio.file.Path) - user11044402
我的操作系统是微软的Windows 10。 - nikli
1个回答

0

Windows 上的默认实现 使用注册表来查找内容类型。您需要创建注册表键 HKEY_CLASSES_ROOT\.yml,并在其下添加一个名为 Content Type 的字符串值,该值是您要用作 MIME 类型的值。您可以将以下内容保存为 yaml.reg 并使用它来为您添加必要的键:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\.yml]
"Content Type"="application/x-yaml"

或者,如果你想使用Files.probeContentType(…),但又不想依赖于提供的默认实现,你可以创建自己的FileTypeDetector
package com.example;

public class CustomFileTypeDetector extends FileTypeDetector
{
    public CustomFileTypeDetector()
    {
    }

    @Override
    public String probeContentType(Path path)
        throws IOException
    {
        // Some error checking omitted for brevity
        String filename = path.getFileName().toString();

        if (filename.endsWith(".yml") || filename.endsWith(".yaml")) {
            // See https://dev59.com/FXRC5IYBdhLWcg3wVvct#332159
            return "application/x-yaml";
        }

        return null;
    }
}

您还需要创建一个文件,以便ServiceLoader可以找到它,因为这是它发现FileTypeDetector实现的方式。假设使用Maven,您将创建一个文件:

src/main/resources/META-INF/services/java.nio.file.spi.FileTypeDetector

通过上面的示例代码,具有以下内容:

com.example.CustomFileTypeDetector

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接