代码如下:
package com.test; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class PropManager { private static final Log log = LogFactory.getLog(PropManager.class); public static Properties prop = null; static { prop = new Properties(); InputStream in=new PropManager().getClass().getResourceAsStream("jdbc.properties"); log.info("start load jdbc.properties config file ! in===== "+in); try { log.info("start load jdbc.properties config file ! "); prop.load(in); log.info("success load jdbc.properties config file done! "); } catch (IOException e1) { e1.printStackTrace(); log.error(" load jdbc.properties config failure! ",e1); } } /** * @param args */ public static void main(String[] args) { String jdbcUrl=prop.getProperty("jdbc.test.url"); String jdbcUsername = prop.getProperty("jdbc.test.username"); String jdbcPassword = prop.getProperty("jdbc.test.password"); System.out.println("jdbcUrl=="+jdbcUrl); System.out.println("jdbcUsername=="+jdbcUsername); System.out.println("jdbcPassword=="+jdbcPassword); System.out.println("jdbcPassword=="+getProp("jdbc.admin.password")); } public static String getProp(String key) { return prop.getProperty(key); } }
属性文件:
jdbc.properties:
内容如下:
#
jdbc.test.url=jdbc:mysql://192.168.0.1:3316/test?characterEncoding=GBK
jdbc.test.username=root
jdbc.test.password=123456
执行:输出:
2012-12-25 18:06:02,711 INFO [main] - com.test.PropManager.<clinit>(20) | start load jdbc.properties config file ! in===== java.io.BufferedInputStream@14d3343
2012-12-25 18:06:02,711 INFO [main] - com.test.PropManager.<clinit>(22) | start load jdbc.properties config file !
2012-12-25 18:06:02,711 INFO [main] - com.test.PropManager.<clinit>(24) | success load jdbc.properties config file done!
jdbcUrl==jdbc:mysql://192.168.0.1:3316/test?characterEncoding=GBK
jdbcUsername==root
jdbcPassword==123456
jdbcPassword==123456
特别注意如下路径写法:
InputStream in=new PropManager().getClass().getResourceAsStream("jdbc.properties");
同时 保持 PropManager类和属性文件jdbc.properties:在一个目录下.