简体   繁体   English

Java返回YAML MIME类型null

[英]Java returns YAML mime type null

Java 8 Files.probeContentType(new File("config.yml").toPath()); Java 8 Files.probeContentType(new File("config.yml").toPath()); returns null . 返回null Why java couldn't find yaml mime type, but can find xml as text/xml ? 为什么Java找不到yaml mime类型,但可以找到xml作为text/xml Is there any other way? 还有其他办法吗?

foo: bar

The default implementation on Windows uses the registry to find the content type. Windows上的默认实现使用注册表来查找内容类型。 You would need to create the registry key HKEY_CLASSES_ROOT\\.yml and add a string value underneath it called Content Type that has the value that you want to use as the MIME type. 您将需要创建注册表项HKEY_CLASSES_ROOT\\.yml并在其下添加一个名为Content Type的字符串值,该字符串值具有您要用作MIME类型的值。 You can save the following as yaml.reg and use it to add the necessary keys for you: 您可以将以下内容另存为yaml.reg并使用它为您添加必要的键:

Windows Registry Editor Version 5.00

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

Alternatively, if you want to use Files.probeContentType(…) but do not want to rely upon the provided default implementation, you can create your own FileTypeDetector : 另外,如果您想使用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;
    }
}

You will also need to create a file that ServiceLoader can find because that is how it discovers implementations of FileTypeDetector . 您还需要创建一个ServiceLoader可以找到的文件,因为这是它发现FileTypeDetector实现的方式。 Assuming maven, you would create a file: 假设使用Maven,您将创建一个文件:

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

With the following content (based on the example code above): 具有以下内容(基于上面的示例代码):

com.example.CustomFileTypeDetector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM