在Groovy中读取YAML文件

时间:2013-08-19 10:10:58

标签: groovy yaml betamax

我正在尝试在Groovy项目中加载现有的YAML文件(使用snakeYaml库)。我有一个名为YamlTape.groovy的类,它包含使用以下代码加载YAML文件的方法。

static YamlTape readFrom(Reader reader) {
    try {
        println "YamlTape : inside readFrom reader.size() = "+reader+" YamlTape: "+YamlTape

        yaml.loadAs(reader, YamlTape)
        println "YamlTape : after readfrom"
    } catch (YAMLException e) {
        println "YamlTape : inside catch block"
        throw new TapeLoadException('Invalid tape', e)
    }
}

并尝试从另一个groovy类调用此方法。

代码:

    YamlTape loadTape(String name) {
    println "YamlTapeLoader : inside loadTape"
    def file = fileFor(name)
    println "YamlTapeLoader : inside loadTape filename -name: "+name
    println "YamlTapeLoader : inside loadTape filename -file: "+file

    file.setReadable(true);
    file.setWritable(true);

    if (file.isFile()) {
        println "YamlTapeLoader : inside file.isFile() : "+file.isFile()
        def tape = file.withReader(FILE_CHARSET) { reader ->
            YamlTape.readFrom(reader)

            println "YamlTapeLoader : inside readFrom : "+reader
        }
        println "YamlTapeLoader : tape : "+tape


        tape
    } else {
        println "YamlTapeLoader : inside ELSE : "
        new YamlTape(name: name)
    }
}

但是load tape方法中的tape变量总是返回null。我添加了一些日志,发现代码能够访问yaml文件,但无法解析Yaml文档并返回为Java Object。

日志是:

YamlTapeLoader : inside loadTape
YamlTapeLoader : inside loadTape filename -name: kar
YamlTapeLoader : inside loadTape filename -file: /Users/Shared/AATest/Record/kar.yaml
YamlTapeLoader : inside file.isFile() : true
YamlTape : inside readFrom reader.size() = java.io.LineNumberReader@34189cab YamlTape: class co.freeside.betamax.tape.yaml.YamlTape
YamlTape : inside getYaml 
YamlTape : representer = co.freeside.betamax.tape.yaml.TapeRepresenter@201a503f
YamlTape : constructor = org.yaml.snakeyaml.constructor.Constructor@16e7eec9
YamlTape : dumperOption = org.yaml.snakeyaml.DumperOptions@39d7af3
YamlTape : after readfrom
YamlTapeLoader : inside readFrom : java.io.LineNumberReader@34189cab
YamlTapeLoader : tape : null

1 个答案:

答案 0 :(得分:2)

withReader块隐式返回闭包的最后一行,在您的情况下是:

        println "YamlTapeLoader : inside readFrom : "+reader

println返回null,因此请将代码更改为:

    def tape = file.withReader(FILE_CHARSET) { reader ->
        def ret = YamlTape.readFrom(reader)
        println "YamlTapeLoader : inside readFrom : "+reader
        ret // Return the result of YamlTape.readFrom
    }

它应该可行

修改

您的readFrom方法具有相同的错误...将其更改为:

static YamlTape readFrom(Reader reader) {
  try {
    println "YamlTape : inside readFrom reader.size() = "+reader+" YamlTape: "+YamlTape

    def ret = Yaml.loadAs(reader, YamlTape)
    println "YamlTape : after readfrom"

    ret // Return the YamlTape
  } catch (YAMLException e) {
    println "YamlTape : inside catch block"
    throw new TapeLoadException('Invalid tape', e)
  }
}