【发布时间】:2017-02-10 04:15:46
【问题描述】:
我试图使用 scala 和如下构造函数调用来读取 YAML 文件
import org.yaml.snakeyaml.constructor.Constructor
import java.io.{File, FileInputStream}
import scala.collection.mutable.ArrayBuffer
import org.yaml.snakeyaml.Yaml
object aggregation {
def main(args:Array[String]) : Unit = {
//val conf = new SparkConf().setAppName("yaml test").setMaster("local[*]")
//val sc = new SparkContext(conf)
val yamlfile = "C:\\Users\\***\\Desktop\\mongoDB\\sparkTest\\project\\properties.yaml"
val input1 = new FileInputStream(new File(yamlfile))
val yaml = new Yaml(new Constructor(classOf[ReadProperties]))
val e = yaml.load(input1).asInstanceOf[ReadProperties]
println(e.file1)
}
}
我有一个单独的类,这样我就可以将 YAML 项目作为 bean,如下所示,
class ReadProperties(@BeanProperty var file1:String,@BeanProperty var file2:String) {
//constructor
}
我的yaml文件(properties.yaml)的内容如下,
file1: C:\\data\\names.txt
file2: C:\\data\\names2.txt
但错误在于
Can't construct a java object for tag:yaml.org,2002:ReadProperties; exception=java.lang.NoSuchMethodException: ReadProperties.<init>()
in 'reader', line 1, column 1:
file1: C:\\data\\names.txt
^
at org.yaml.snakeyaml.constructor.Constructor$ConstructYamlObject.construct(Constructor.java:350)
at org.yaml.snakeyaml.constructor.BaseConstructor.constructObject(BaseConstructor.java:182)
但是如果我使用下面的代码它可以工作(没有构造函数类),
val yaml = new Yaml
val obj = yaml.load(input)
val e = obj.asInstanceOf[java.util.HashMap[String,String]]
println(e)
result :
{file1=C:\\data\\names.txt, file2=C:\\data\\names2.txt}
16/10/02 01:24:28 INFO SparkContext: Invoking stop() from shutdown hook
我希望我的构造函数工作,并希望直接引用 yaml 属性文件中的参数值。 (比如yaml文件“file1”和“file2”有两个参数所以想直接引用)
任何帮助将不胜感激。提前致谢!
【问题讨论】:
标签: scala constructor yaml snakeyaml