Java学习 IO Properties类

特点:

      1,该集合的键和值都是字符串类型

      2,该集合的数据可以保存在流中,或者从流获取

通常该集合用于操作以键值对形式存在的配置文件

public static void main(String[] args) throws IOException {
		Properties p = new Properties();
		p.setProperty("张三", "23");
		p.setProperty("李四", "35");
		p.setProperty("王五", "19");
		p.setProperty("赵六", "22");
		
		Set<String> names = p.stringPropertyNames();
		for(String name : names){
			String value = p.getProperty(name);
			System.out.println(name+":"+value);
		}
	}

结果:
赵六:22
王五:19
张三:23
李四:35

list方法:


	public static void main(String[] args) throws IOException {
		Properties p = new Properties();
		p.setProperty("张三", "23");
		p.setProperty("李四", "35");
		p.setProperty("王五", "19");
		p.setProperty("赵六", "22");
//		将属性列表输出到指定的输出流。此方法对调试很有用。
		p.list(System.out);
	}


结果:
-- listing properties --
赵六=22
王五=19
张三=23
李四=35

store方法:

public static void main(String[] args) throws IOException {
		Properties p = new Properties();
		p.setProperty("张三", "23");
		p.setProperty("李四", "35");
		p.setProperty("王五", "19");
		p.setProperty("赵六", "22");
		
		//将集合数据持久化 保存在硬盘的文件中
//		FileOutputStream fos = new FileOutputStream("C:\\Users\\悠悠华\\Desktop\\test\\ccc.txt");
//		
//		p.store(fos, "随便来一下");
		
		FileWriter fw = new FileWriter("C:\\Users\\悠悠华\\Desktop\\test\\ccc.txt");
		p.store(fw, "this is message");
	}

结果:

修改配置信息

配置文件

public static void main(String[] args) throws IOException {
		//新建一个文件对象
		File file = new File("C:\\Users\\悠悠华\\Desktop\\test\\ccc.txt");
		//新建一个输入流与文件对象相关联
		FileInputStream fis = new FileInputStream(file);
		//新建一个属性对象
		Properties p = new Properties();
		//先将文件对象的数据存入这个属性对象中
		p.load(fis);
		
		//先测试一下 属性对象的键值对有哪些
		p.list(System.out);
		
		//重新设置 this 键的值 将其改为 789
		p.setProperty("this", "789");
		
		//再次测试一下 属性对象的键值对有哪些
		p.list(System.out);
		//新建一个输出流
		FileOutputStream fos = new FileOutputStream(file);
		//将属性对象的键值对持久化 存储到文件中
		p.store(fos, "heihei");
		
		//关闭流
		fis.close();
	}

结果:

-- listing properties --
b=3
this=456
a=2
-- listing properties --
b=3
this=789
a=2

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值