Java中如何读取和写入properties文件

 properties文件是一种属性文件,这种文件以key=value格式存储内容。Java中可以使用Properties类来读取这个文件,一般properties文件作为一些参数的存储,使得代码更加灵活。
这里先定义一个data.properties文件,内容如下:

cn=12
kr=14
jp=64

既然properties是一个文件,那么我们也可以用FileInputStreram来进行读取:

	try (BufferedInputStream bis = new BufferedInputStream(new  FileInputStream("D:\\test\\data.properties"))) {
		int data = -1;
		while((data = bis.read()) != -1) {
			System.out.print((char)data);
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
		
    运行结果
    // cn=12
    // kr=14
    // jp=64

但是,由于properties文件中每一行都是独立的键值对,这种普通读取方式并没有按照键值对的方式进行读取,而是逐个字节读取,对于这种文件来讲是没有意义的。

所以就应该使用Properties类来进行读取,从jdk源码中可以看出,Properties继承自Hashtable,因此,Properties也同样有put和get方法,由于,properties是一个文件,Properties类提供了一个load()方法,InputStram作为数据源,传入一个输入流,把输入流中的内容传入到内部的key和value中,然后就能读取到properties文件中的内容了。代码如下:

	// Properties格式文件的写入
    try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\test\\data.properties"))) {
		Properties props = new Properties();
			
		props.load(bis); // 将“输入流”加载至Properties集合对象中
			
		// 根据key,获取value
		System.out.println("cn");
			
	} catch (IOException e) {
		e.printStackTrace();
	}

    // 运行结果
    // cn=12

同样,在写properties文件时,Properties类也提供了store()方法,OutputStream和String类型的注释作为数据源,将内部的键值对集合和注释传入到输出流中,就可以进行写入操作了。代码如下:

	// Properties格式文件的写入
	try {
		Properties props = new Properties();
		props.put("F1", "2314");
		props.put("F2", "2341");
		props.put("F3", "5322");
		props.put("F4", "4316");
			
		// 使用“输出流”,将Properties集合中的KV键值对,写入*.properties文件
		try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\test\\demo.properties"))){
			props.store(bos, "just do IT");
		}
	} catch (IOException e) {
		e.printStackTrace();
	}

可以看到,demo.properties文件已经被创建出来了,内容包括注释、创建时间和每对键值对 。

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

仙草不加料

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

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

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

打赏作者

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

抵扣说明:

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

余额充值