Properties类小结

本文详细介绍了Java中Properties类的基本用法,包括从输入流加载属性文件、读取属性值、获取所有键、修改值、存储到输出流及清空属性等操作。

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

目前有个任务,要用到java.util.Properties类及其拓展知识.在这里先把预备知识梳理一下,过几天再把commons configuration整理出来.

一.Properties 简介
java.util.Properties 继承自 java.util.Hashtable
Properties 类表示一个持久的属性集.Properties 可保存在流中或从流中加载.属性列表中每个键及其对应值都是一个字符串.

二.基本方法
2.1 如何从输入流中加载属性文件
使用load(InputStream is)方法:

Properties properties = new Properties();
InputStream is = new FileInputStream("conn.properties");
properties.load(is);
is.close();


2.2 如何读属性文件中的值
使用getProperties(String key)方法:

String temp = properties.getProperties(String key);


<注>重载的方法getProperties(String key, String default)方法 将在查询不到值的情况下,返回default.
即: 如果 null == properties.getProperties(String key);
则有 default == properties.getProperties(String key, String default);

2.3 如何获取属性文件中的所有的键
使用propertyNames()方法,该方法返回是键的枚举.

Enumeration enumeration = properties.propertyNames();


2.4 如何修改属性文件中的值
使用
setProperties(String key, String value)
方法.
<注>该方法调用的 Hashtable 的put方法.如果键存在,则修改值;如果键不存在,则添加值.

2.5 如何存储属性文件到输出流
使用store(OutputStream os, String description)方法:

Properties properties = new Properties();
OutputStream os = new FileOutputStream("test.properties");
String description = "store properties to test.properties";
properties.store(os, description);
os.close();


2.6 如何清空所有值
使用
clear()
方法.
<注>该方法继承自 Hashtable 的clear()方法.清空哈希表.

三.实例附件
<注>实例中没有指明properties文件的绝对路径.那么默认是在项目根目录下的.
当生成新文件时,使用F5刷新就能看见新文件产生了.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值