end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

snakeyaml for java による yaml load/read

javaにおけるyaml用ライブラリはいくつもあるようですが、何となく今日はsnakeYAML.

package jp.end0tknr;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.yaml.snakeyaml.Yaml;

public class TestSnakeYaml {
    public TestSnakeYaml() {}

    public static void main(String[] args) {
        String confFilePath = "resource/test.yaml";
        String encoding = "UTF-8";
        
        File file = new File(confFilePath);
        FileInputStream input;
        InputStreamReader stream;
        try {
            input = new FileInputStream(file);
            stream = new InputStreamReader(input,encoding);
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            System.out.println(e.getClass().getName()+ 
                    " fail open file "+ confFilePath);
            return;
        }        
        
        Yaml yaml = new Yaml();
        Map yamlMap = (Map<String, ?>) yaml.load(stream);

        for(Object atriKeyTmp : yamlMap.keySet() ){
            String atriKey = (String) atriKeyTmp;
            System.out.println( yamlMap.get(atriKey).toString() );
        }
    }
}
common:
  system_name: ほげほげ
  encode: utf8
  #yes/no
#  debug_mode: yes
db:
  host: localhost
  port: 3306
  db_name: testdb
  db_user: root
  db_pass: 
  db_opt:
    AutoCommit: 0
    mysql_enable_utf8: 1
  client_encoding: utf8

↑こう書くと、↓こう表示されます

{system_name=ほげほげ, encode=utf8}
{host=localhost, port=3306, db_name=testdb, db_user=root, db_pass=null, db_opt={AutoCommit=0, mysql_enable_utf8=1}, client_encoding=utf8}

利用したjar

  • snakeyaml-1.18.jar