文章目录
properties 介绍
Properties 继承于 Hashtable.表示一个持久的属性集.属性列表中每个键及其对应值都是一个字符串。
Properties(Java.util.Properties),该类主要用于读取Java的配置文件,不同的编程语言有自己所支持的配置文件,配置文件中很多变量是经常改变的,为了方便用户的配置,能让用户够脱离程序本身去修改相关的变量设置。就像在Java中,其配置文件常为.properties文件,是以键值对的形式进行参数配置
使用方法
除了从Hashtable中所定义的方法,Properties定义了以下方法:
序号 | 方法描述 |
---|---|
1 | String getProperty(String key) 用指定的键在此属性列表中搜索属性。 |
2 | String getProperty(String key, String defaultProperty) 用指定的键在属性列表中搜索属性。 |
3 | void list(PrintStream streamOut) 将属性列表输出到指定的输出流。 |
4 | void list(PrintWriter streamOut) 将属性列表输出到指定的输出流。 |
5 | void load(InputStream streamIn) throws IOException 从输入流中读取属性列表(键和元素对)。 |
6 | Enumeration propertyNames( ) 按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)。 |
7 | Object setProperty(String key, String value) 调用 Hashtable 的方法 put。 |
8 | void store(OutputStream streamOut, String description) 以适合使用 load(InputStream)方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。 |
常用方法示例
(1)load(InputStream inStream)
这个方法可以从.properties属性文件对应的文件输入流中,加载属性列表到Properties类对象。如下面的代码:
Properties pro = new Properties();
FileInputStream in = new FileInputStream(“a.properties”);
pro.load(in);
in.close();
(2)store(OutputStream out, String comments)
这个方法将Properties类对象的属性列表保存到输出流中。如下面的代码:
FileOutputStream oFile = new FileOutputStream(file, “a.properties”);
pro.store(oFile, “Comment”);
oFile.close();
如果comments不为空,保存后的属性文件第一行会是#comments,表示注释信息;如果为空则没有注释信息。
注释信息后面是属性文件的当前保存时间信息。
(3)getProperty/setProperty
这两个方法是分别是获取和设置属性信息。
读取jdbc的properties实例
public Connection getConnection() throws Exception{
Properties info=new Properties();
info.load(this.getClass().getClassLoader().getResourceAsStream("jdbc.properties"));
String driver=info.getProperty("driver");
String jdbcUrl=info.getProperty("jdbcUrl");
String user=info.getProperty("user");
String password=info .getProperty("password");
Class.forName(driver);
Connection connection=DriverManager.getConnection(jdbcUrl,user,password);
return connection;
}