如果条件为Yaml文件 - Java

时间:2016-11-15 20:18:11

标签: java yaml

我有Yaml文件:

#Define CDN domains
---
CDN: 
 quality: 200..300
 cost: low
 Video-type: mp4

使用此Java代码,我检索CDN的子值:

 // The path of your YAML file.

 Yaml yaml = new Yaml();

 Map<String, Map<String, String>> values =
  (Map<String, Map<String, String>>) yaml
    .load(new FileInputStream(new File("/workspace/servlet-yaml/src/test.yaml")));

for (String key : values.keySet()) {
  Map<String, String> subValues = values.get(key);
  for (String subValueKey : subValues.keySet()) {
    System.out.println(values); 
  }
}

输出结果为:

{CDN={quality=200..300, cost=low, Video-type=mp4}}
{CDN={quality=200..300, cost=low, Video-type=mp4}}
{CDN={quality=200..300, cost=low, Video-type=mp4}}
  • 首先,我不知道为什么会重复三次?
  • 其次,我想编写一个代码 if cost = low,然后做某事。

1 个答案:

答案 0 :(得分:0)

  

首先,我不知道它有三次重新评估吗?

因为你告诉它。 对于每个subValueKey,打印整个值集。有三个子键,因此完整的值集打印三次。

  

其次,我想写一个代码,如果成本=低,那么做一些事情。

Yaml yaml = new Yaml();

Map<String, Map<String, String>> values =
        (Map<String, Map<String, String>>) yaml.load(
        new FileInputStream(new File(
        "/workspace/servlet-yaml/src/test.yaml")));

final Map<String, String> cdn = values.get("CDN");
    // or iterate over all keys like you currently do
final String cost = cdn.get("cost");
    // or iterate over all subkeys and compare them to "cost".
    // that way, it's easier to handle missing keys.
if ("low".equals(cost)) {
    // do something
}