有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么YAMLGenerator不关闭流取决于配置

使用yaml factory创建objectMapper时,您可以设置两个配置参数:

   ObjectMapper o = new ObjectMapper(new YAMLFactory());
    // o.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    // o.enable(SerializationFeature.CLOSE_CLOSEABLE);

问题是YAML生成器中忽略了此配置:

 @Override
    public void close() throws IOException
    {
        if (!isClosed()) {
            _emitter.emit(new DocumentEndEvent(null, null, false));
            _emitter.emit(new StreamEndEvent(null, null));
            super.close();
            _writer.close();
        }
    }

即使在javadoc中写的是其他东西

void com.fasterxml.jackson.dataformat.yaml.YAMLGenerator.close() throws IOException

Method called to close this generator, so that no more content can be written.

Whether the underlying target (stream, writer) gets closed depends on whether this generator either manages the target (i.e. is the only one with access to the target -- case if caller passes a reference to the resource such as File, but not stream); or has feature Feature.AUTO_CLOSE_TARGET enabled. If either of above is true, the target is also closed. Otherwise (not managing, feature not enabled), target is not closed.


共 (1) 个答案

  1. # 1 楼答案

    使用YAML映射器而不是对象映射器。这对我来说很好

    YAMLMapper yamlMapper = new YAMLMapper(); 
    yamlMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); 
    yamlMapper.configure(YAMLGenerator.Feature.WRITE_DOC_START_MARKER, true);
    yamlMapper.enable(SerializationFeature.CLOSE_CLOSEABLE);