Java Properties

来源:互联网 发布:手机app软件下载 编辑:程序博客网 时间:2024/05/16 01:34

1 Properties类的作用

    在我们平时写程序的时候,有些参数是经常改变的,而这种改变不是我们预知的。比如说我们开发了一个操作数据库的模块,在开发的时候我们连接本地的数据库那么 IP ,端口号,数据库名称等信息并不是固定不变的,要使得这个操作数据的模块具有通用性,那么以上信息就不能写死在程序里。通常我们的做法是用配置文件来解决。 Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,在Java中,其配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。

2 几个重要方法

    继承结构:

(1)void load(InputStream inStream)                         从输入字节流中加载属性列表(键值对)
(2)String getProperty(String key)                              根据key获得对应的value
(3)Object setProperty(String key, String value)      调用 Hashtable 的 put方法,设置键值对。
(4)store(OutputStream out, String comments)        将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键值对写入到指定的文件中。
(5)void clear()                                                                调用父类Hashtable的clear方法,清除键值对列表
(6)Enumeration<?> propertyNames()                      Returns an enumeration of all the keys in this property list
(7)void list(PrintStream out)                                        Prints this property list out to the specified output stream
(8) boolean containsKey(Object key)                       父类的containsKey方法,判断是否有指定的键

3 代码实现

package pkgOne;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.util.Enumeration;import java.util.Properties;public class LearnProperties {private static Properties properties=new Properties();public static void loadProperties() throws Exception{FileInputStream fileInput=new FileInputStream("e:/123.txt");BufferedInputStream bufferedInput=new BufferedInputStream(fileInput);properties.load(bufferedInput);bufferedInput.close();fileInput.close();}public static String getValue(String key) {if(properties.containsKey(key))return properties.getProperty(key);else {return "";}}public static void setValue(String key,String value) {properties.setProperty(key, value);}public static void saveProperties() throws Exception {FileOutputStream fileOutput=new FileOutputStream("e:/123.txt");BufferedOutputStream out=new BufferedOutputStream(fileOutput);properties.store(out, "存储properties到指定文件");out.close();fileOutput.close();}public static void getAllProperties() {Enumeration<?> enumeration=properties.propertyNames();while (enumeration.hasMoreElements()) {String key = (String) enumeration.nextElement();String value=properties.getProperty(key);System.out.println("key:"+key+",value="+value);}}public static void printProperties() {properties.list(System.out);}public static void clearProperties() {properties.clear();}public static void main(String[] args) throws Exception{loadProperties();printProperties();System.out.println(getValue("name"));getAllProperties();setValue("sex", "man");getAllProperties();saveProperties();}}


0 0