服务器之家

服务器之家 > 正文

浅谈java Properties类的使用基础

时间:2021-03-14 11:57     来源/作者:骏马金龙

Properties继承自HashTable,通常和io流结合使用。它最突出的特点是将key/value作为配置属性写入到配置文件中以实现配置持久化,或从配置文件中读取这些属性。它的这些配置文件的规范后缀名为".properties"。表示了一个持久的属性集。

需要注意几点:

无论是key还是value,都必须是String数据类型。

虽然继承自HashTable,但它却没有使用泛型。

虽然可以使用HashTable的put方法,但不建议使用它,而是应该使用setProperty()方法。

多个线程可以共享单个Properties对象而无需进行外部同步。即线程同步。

如果想将Properties集合中的属性集写入到配置文件中,使用store()方法;如果想从".properties"配置文件中读取属性,可以使用load()方法。

以下是Properties类的常用方法:

setProperty(String k,String v):调用hashtable的put方法,向properties集合中添加key/value,返回值为key对应的旧值,如没有旧值则返回Null。注意k和v都是String类型。

getProperty(String k):获取properties集合中key对应的value。

store(OutputStream o,String comment):将properties属性集合写入到输出流o中,注意,注释comment必不可少。 - load(InputStream i):从.properties配置文件中按照字节读取其中的属性。

load(Reader r):从.properties配置文件中按照字符读取其中的属性。

stringPropertyNames():返回properties集合中由key部分组成的Set集合。

以下是向properties集合中增、取、遍历key/value以及和IO流结合使用的简单示例。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.util.*;
import java.io.*;
public class Prop {
 public static void main(String[] args) throws IOException {
 Properties prop = new Properties();
 //向properties集合prop中存储key/value
 prop.setProperty("filename","a.avi");
 prop.setProperty("size","5M");
 //prop集合存储key/value的格式
 System.out.println(prop);
 //从prop中取出单个key/value
 prop.getProperty("filename");
 //遍历prop集合
 Set<String> keys = prop.stringPropertyNames();
 for (String key : keys) {
  String value = prop.getProperty(key);
  System.out.println(key+"="+value);
 }
 //properties集合和IO输出流集合:将prop集合中的属性集写入到文件中实现持久化
 FileOutputStream fos = new FileOutputStream("d:/temp/my.properties");
 prop.store(fos,"store test");
 //properties集合和IO输出流集合:从properties文件中读取属性集到prop1集合中
 //FileInputStream fis = new FileInputStream("d:/temp/my.properties");
 FileReader fr = new FileReader("d:/temp/my.properties");
 Properties prop1 = new Properties(); //Now it's a Null properties
 prop1.load(fr);
 System.out.println("new prop:"+prop1);
 fos.close();
 fr.close();
 }
}

以上这篇浅谈java Properties类的使用基础就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/f-ck-need-u/p/8177766.html

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部