【问题标题】:Java returns YAML mime type nullJava 返回 YAML mime 类型 null
【发布时间】:2020-01-09 09:36:51
【问题描述】:

Java 8 Files.probeContentType(new File("config.yml").toPath()); 返回 null。 为什么java找不到yaml mime类型,但可以找到xml为text/xml?有没有其他办法?

foo: bar

【问题讨论】:

标签: java yaml mime-types


【解决方案1】:

The default implementation on 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://stackoverflow.com/a/332159/21926
            return "application/x-yaml";
        }

        return null;
    }
}

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

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

具有以下内容(基于上面的示例代码):

com.example.CustomFileTypeDetector

【讨论】:

    猜你喜欢
    • 2012-03-28
    • 2011-08-21
    • 2021-09-13
    • 1970-01-01
    • 2016-08-18
    • 2010-09-13
    • 2018-01-03
    • 1970-01-01
    • 2016-05-11
    相关资源
    最近更新 更多