Java中如何对properties文件的操作

1. 资源文件所存放的位置 

资源文件妨碍classpath下,即工程项目的class包下 


2. 获取系统资源文件的方式有2中 

a. 通过 InputStream inputstream = ClassLoader.getSystemResourceAsStream("info.properties"); 

b. 通过 InputStream inputstream = this.getClass().getResourceAsStream("/info.properties"); 

采用第一种方式获取资源文件时,文件不以"/" 开头,而采用方法b的话,文件必须"/"开头 


3. 提取加载资源文件的信息

Java代码

Properties properties = new Properties();
		InputStream inputstream = ClassLoader.getSystemResourceAsStream("info.properties");
		// InputStream inputstream = this.getClass().getResourceAsStream("/info.properties");
		properties.load(inputstream);


4. 操作资源文件 

a. 根据key值在资源文件中查询value值 

    1. getProperty(String key) 用指定的键在此属性列表中搜索属性。 

    2. getProperty(String key, String defaultValue) 用指定的键在属性列表中搜索属性。 

b. 获取所有的键值对的信息
Java代码

Enumeration<String> enumvalue = (Enumeration<String>) properties.propertyNames();
		// 返回属性列表中所有键的枚举,如果在主属性列表中未找到同名的键,则包括默认属性列表中不同的键
		while (enumvalue.hasMoreElements()) {
			String key = enumvalue.nextElement();
			System.out.println(key + " : " + properties.getProperty(key));
		}

c. 向资源文件中添加键值信息,如果key值相同就会将原有的信息覆盖

Java代码

		URL url = ClassLoader.getSystemResource("info.properties");
		File file = new File(url.toURI());
		InputStream is = new FileInputStream(file);
		properties.load(is);
		properties.setProperty("key", "value");
		OutputStream fos = new FileOutputStream(file);
		properties.store(fos, null);
		fos.flush();
		is.close();


d. 删除相关的键值对
Java代码

		File file = new File(ClassLoader.getSystemResource("info.properties").toURI());
		InputStream is = new FileInputStream(file);
		properties.load(is);
		properties.remove("key");
		OutputStream fos = new FileOutputStream(file);
		properties.store(fos, null);
		is.close();
		fos.flush();
		fos.close();
		File file = new File(ClassLoader.getSystemResource("info.properties").toURI());
		InputStream is = new FileInputStream(file);
		properties.load(is);
		properties.remove("key");
		OutputStream fos = new FileOutputStream(file);
		properties.store(fos, null);
		is.close();
		fos.flush();
		fos.close();










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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值