黑马程序员——JAVA学习笔记(十)

------- android培训java培训、期待与您交流! ----------

十、Properties类

Properties是hashtable的子类。
也就是说它具备map集合的特点。而且它里面存储的键值都是字符串。

是集合中和IO技术相结合的集合容器。

该对象的特点:可以用于键值对形式的配置文件。


10.1、Properties存取

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

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


示例如下:

class Properties
{
	public static void main(String[] args)  
	{
		setAndGet()
	}

	//设置和获取元素
	public static void setAanGet()
	{
		Propertise prop = new Propertise();
		
		prop.setProperty("zhangsan","23");
		prop.setProperty("lisi","53");

		String value = prop.getProperty("lisi");

		prop.setProperty("lisi","13");

		Set<String> names = prop.stringPropertyNames();
		for(String s: name)
		{
			System.out.print(s + ":" + prop.getProperty(s));
		}
	}
}

10.2、Properties存取配置文件

如何将流中的数据存储到集合中。

1、用一个流和文件关联。

2、读取一行数据,将文件数据用“=”进行切割。

3、等号左边为键,右边为值。存入到Properties集合中即可。


使用示例1:

class Properties
{
	public static void main(String[] args) throws IOException  
	{
		method()
	}

	//存储流中的数据到集合中
	public static void method() throws IOException
	{
		BufferedReader bufr = new BufferedReader (new FileReader("info.txt"));
		String line = null;
		Properties prop = new Properties();

		while((line = bufr.readLine())!=null)
		{
			String[] arr = line.split("=");
			prop.setProperty(arr[0],arr[1]);
		}
		
		bufr.close();
		System.out.print(prop);
	}
}

使用示例2:

class Properties
{
	public static void main(String[] args) throws IOException  
	{
		loadDemo()
	}

	//存储流中的数据到集合中
	public static void loadDemo() throws IOException
	{
		Properties prop = new Properties();
		FileInputStream fis = new FileInputStream ("info.txt");
		
		//将流中的数据加载进集合
		prop.load(fis);

		prop.setProperty("mazi","51");
		FileOutputStream fos = new FileOutputStream ("info.txt");

		prop.store(fos,"haha");

		prop.list(System.out);
		
		fos.close();
		fis.colse();
	}
}
java1.6以上才使用的方法。


总结:在加载数据时,需要数据有固定格式:键=值。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值