以下是程式碼
PropertyUtils.java
import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Properties; /** * * @author bert */ public class PropertyUtils { // private static final Logger log = LoggerFactory.getLogger(PropertyUtils.class); public PropertyUtils(){ } /** * 透過Key取得參數 * @param key * @return String */ public static String getPropert(String key){ String result = null; try { Properties prop = new Properties(); String propFileName = "config.properties"; InputStream is = PropertyUtils.class.getClassLoader(). getResourceAsStream(propFileName); prop.load(is); if (is == null) { throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath"); } Date time = new Date(System.currentTimeMillis()); // get the property value and print it out result = prop.getProperty(key); if(is != null){ is.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } }
使用方式
private final String DB_Name = PropertyUtils.getPropert("db_name"); private final String IP = PropertyUtils.getPropert("db_location"); private final String USER = PropertyUtils.getPropert("db_user"); private final String PSW = PropertyUtils.getPropert("db_password");
config.properties
db_user = dbuser
db_password = abcd1234
db_location=192.168.1.100
db_name=DemoDB
沒有留言:
張貼留言