java properties 符号,Java Properties集合基础解析

Java Properties集合基础解析

本期学习的properties集合是项目中经常用到的操作

什么是Properties集合?

java.util.Properties集合继承于Hashtable,来表示一个持久的属性集,他使用键值结构存储数据,每个键及其对应的值都是一个字符串,该类被许多java类使用,比如获取系统属性时,System.getProperties,方法就是返回一个Properties对象

properties集合是唯一一个与IO流相结合的集合

可以使用Properties集合中的方法store把集合中的数据持久化

可以使用Properties集合中的load方法,把硬盘中保存的文件(键值对)存储到集合中使用,这在项目中 用于读取配置文件经常使用到

属性表中每个键及其对应值都是一个字符串

Properties集合是一个双列集合(双列集合是每个元素由键和值两部分组成,由键可以找到值,键必须是唯一的,值可以重复)

构造方法

public properties() 创建一个空的属性列表

基本的存储方法:

public Object setProperty(String key,String value) :保存一对属性

public String setProperties(String key) :使用此属性列表中指定的键搜索属性值

public Set

stringPropertNames() 获取所有名称的集合

public class Main {

public static void main(String[] args) {

Properties properties = new Properties();

//存入键值对

properties.setProperty("one","1");

properties.setProperty("two","2");

//拿出所有键

Set strings = properties.stringPropertyNames();

//遍历键

for (String string : strings) {

//通过键获取值

String property = properties.getProperty(string);

//输出

System.out.println(string+":"+property);

}

}

}

结果

da45960007e5750ce25d2d5aeb440082.png

与流相关的方法

store ( OutputStream out, String comments)

store ( OutputStream out, String comments) : 以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。

参数中使用了字节输入流,通过流对象,可以关联到某文件上,这样就可以能够加载文本中的数据了,文本数据格式:

public class Main {

public static void main(String[] args) throws IOException {

Properties properties = new Properties();

//存入键值对

properties.setProperty("one","1");

properties.setProperty("two","2");

//加载文本中信息到属性集

properties.store(new FileWriter("c.text"),"savedate");

//拿出所有键

Set strings = properties.stringPropertyNames();

}

}

结果

3bef1d2af9b4707b08f8e9d0dd505003.png

public void load(InputStream inStream)

public void load(InputStream inStream) : 从字节输入流中读取键值对。

注意:

1.存储键值对的文件中,键与值默认的链接符号可以使用=,空格等其他符号

2.存储键值对的文件中,可以使用“#”进行注释,被注释的键值对默认不会被读取

3.存储键值对的文件中,键与值都是字符串,不要加引号

public class Main {

public static void main(String[] args) throws IOException {

Properties properties = new Properties();

properties.load(new FileReader("c.text"));

//拿出所有键

Set strings = properties.stringPropertyNames();

for (String string : strings) {

System.out.println(string+":"+properties.getProperty(string));

}

}

}

结果

ea93a7e6f3e91a48dab22fc0f4d250f7.png

以上就是Properties集合的一些基础知识,如有错误请各位批评指正,喜欢我的文章可以点赞收藏,我会不定期更新文章,各位道友也可以关注我

a3caf58957f938d3e18b34caf9e29f59.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值