YAMLのJava実装——JYAML基本原理と例(3)YAMLのファイルフローに対する処理
先に読んでください
「YAMLのJava実装——JYAML基本原理と例(1)導出データはYAML形式ファイル」
「YAMLのJava実現——JYAML基本原理と例(2)YAML形式ファイルの導入」
1.FileOutputStream
YAMLファイルにデータを流し込む。
流れのようにYAMLファイルからデータを読み込みます。
「YAMLのJava実装——JYAML基本原理と例(1)導出データはYAML形式ファイル」
「YAMLのJava実現——JYAML基本原理と例(2)YAML形式ファイルの導入」
1.FileOutputStream
YAMLファイルにデータを流し込む。
/* Output data structure into a YAML file as a FileOutputStream. */
try {
YamlEncoder yEncoder = new YamlEncoder(new FileOutputStream(dumpFile));
for (int i = 0; i < 3; ++i) {
michael.setAge(24 + i);
yEncoder.writeObject(michael);
yEncoder.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
2.FileInputStream流れのようにYAMLファイルからデータを読み込みます。
/* Input a YAML file into data structure as a FileOutputStream. */
try {
YamlDecoder yDecoder = new YamlDecoder(new FileInputStream(dumpFile));
Person[] persons = {new Person(), new Person(), new Person()};
for (int i = 0; i < 3; ++i) {
persons[i] = (Person) yDecoder.readObject();
System.out.println();
TestYaml.output(persons[i]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (EOFException e) {
e.printStackTrace();
}
3.YAMLファイルを確認する--- &0 !com.sinosuperman.yaml.Person
age: 24
children: &2 !com.sinosuperman.yaml.Person[]
- !com.sinosuperman.yaml.Person
age: 3
name: boy
- !com.sinosuperman.yaml.Person
age: 1
name: girl
name: Michael Corleone
spouse: !com.sinosuperman.yaml.Person
age: 24
children: *2
name: Floveria Edie
spouse: *0
--- &9 !com.sinosuperman.yaml.Person
age: 25
children: &11 !com.sinosuperman.yaml.Person[]
- !com.sinosuperman.yaml.Person
age: 3
name: boy
- !com.sinosuperman.yaml.Person
age: 1
name: girl
name: Michael Corleone
spouse: !com.sinosuperman.yaml.Person
age: 24
children: *11
name: Floveria Edie
spouse: *9
--- &18 !com.sinosuperman.yaml.Person
age: 26
children: &20 !com.sinosuperman.yaml.Person[]
- !com.sinosuperman.yaml.Person
age: 3
name: boy
- !com.sinosuperman.yaml.Person
age: 1
name: girl
name: Michael Corleone
spouse: !com.sinosuperman.yaml.Person
age: 24
children: *20
name: Floveria Edie
spouse: *18