今天嘗試了下使用JYaml類庫解析Yaml文檔。java
現有Yaml文檔.travis.yml以下:oracle
language: java sudo: false cache: directories: - $HOME/.m2 jdk: - oraclejdk8 - oraclejdk7 - openjdk7 script: - mvn clean install -Pqulice --errors --batch-mode
使用JYaml類庫中的函數 YamlStream org.ho.yaml.Yaml.loadStream(File arg0) 能夠將yml文檔中內容讀取到流中。函數
Java代碼以下:code
import java.io.File; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.ho.yaml.Yaml; import org.ho.yaml.YamlStream; /** * * @author Tsybius2014 * @date 2016年3月2日 * @time 下午10:35:50 * @remark * */ public class JyamlTest { /** * 使用JYaml解析YAML文檔 * @param args */ @SuppressWarnings("rawtypes") public static void main(String[] args) { try { File file = new File(".travis.yml"); YamlStream stream = Yaml.loadStream(file); for (Iterator iter = stream.iterator(); iter.hasNext();) { HashMap hashMap = (HashMap) iter.next(); // System.out.println(hashMap); for (Iterator iter2 = hashMap.entrySet().iterator(); iter2.hasNext();) { Map.Entry entry = (Map.Entry) iter2.next(); Object key = entry.getKey(); Object value = entry.getValue(); System.out.println("key's type = " + key.getClass()); System.out.println("value's type = " + value.getClass()); System.out.println("key = " + key + ", value = " + value); System.out.println("================================="); } } } catch (Exception e) { e.printStackTrace(); } } }
文檔讀取到一個HashMap中,每一個key都是一個字符串,每一個value視yaml文檔實際狀況而定。ip
上面的代碼輸出結果爲:rem
key's type = class java.lang.String value's type = class java.util.ArrayList key = jdk, value = [oraclejdk8, oraclejdk7, openjdk7] ================================= key's type = class java.lang.String value's type = class java.util.HashMap key = cache, value = {directories=[$HOME/.m2]} ================================= key's type = class java.lang.String value's type = class java.lang.String key = language, value = java ================================= key's type = class java.lang.String value's type = class java.lang.Boolean key = sudo, value = false ================================= key's type = class java.lang.String value's type = class java.util.ArrayList key = script, value = [mvn clean install -Pqulice --errors --batch-mode] =================================
END文檔