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


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

钟超

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值