Properties的使用

本文详细介绍了Java中Properties类的使用方法,包括如何加载属性文件、修改属性值并保存回文件,以及从流中读取键值对到Properties集合中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
Properties 类表示了一个持久的属性集,是hashtable的子类
也就是说它具备Map集合的特点为,而且它里面存储的键值对都是字符串

是集合中和io技术相合的集合容器
该对象的特点,可以用键值对形式的配置文件
那么在加载数据时,需要数据固定格式:键=值。

*/
import java.util.*;
import java.io.*;

class  PropertiesDemo
{
	public static void main(String[] args) throws IOException
	{
//		setAndGet();
	//	fileToProperty();
		 loadProperty();
	}

	//演示Properties 加载流中的数据 和 把流中的数据存储到文件中
	public static void loadProperty()throws IOException
	{
		Properties prop = new Properties();
		FileInputStream fis = new FileInputStream("info.ini");
		//将流中的数据加载进集合
		prop.load(fis); 
		//改变内存中的结果。
		prop.setProperty("ah","09");
			
		//fis.close();
		FileOutputStream fout = new FileOutputStream("info.ini");
		prop.store(fout,"注释信息");

		fis.close();
		fout.close();

		System.out.println(prop);	
		
	}

	//演示,如何将流中的数据存储到集合中
	//想要将info.ini 中键值数据存储到集合中进行操作
	/*
		思路:
		1:用一个流和info.ini文件关联
		2:读取一行数据,将该行数据用“="进行分割
		3:等号左边作为键,右边作为值。存入到Properties集合中。
	*/
	public static void fileToProperty()throws IOException
	{
		BufferedReader br = new BufferedReader(new FileReader("info.ini"));
		String line = null;
		Properties prop = new Properties();

		while((line = br.readLine())!=null)
		{
			String[] arr = line.split("=");	//分割
			System.out.println(arr[0]+"..."+arr[1]);
			prop.setProperty(arr[0],arr[1]);
		}
		br.close();
	}

	//设置和获取元素
	public static void setAndGet()
	{
		Properties prop = new Properties();

		prop.setProperty("zhangsan","20");
		prop.setProperty("lisi","30");
	
//		System.out.println(prop);
		String value = prop.getProperty("lisi");
		System.out.println(value);

		//返回此属性列表中的键集,其中该键及其对应值是字符串
		Set<String> setProp = prop.stringPropertyNames();
		
		for(String temp : setProp)
		{
			System.out.println(temp+": "+prop.getProperty(temp));
		}

	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值