YAML的Java实现——JYAML基本原理与示例(3)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


你可能感兴趣的:(API,-,YAML)