使用JavaSE API讀取Properties文件的六種方法
1。使用java.util.Properties類的load()方法
示例: InputStream in = lnew BufferedInputStream(new FileInputStream(name));
Properties p = new Properties();
p.load(in);
2。使用java.util.ResourceBundle類的getBundle()方法
示例: ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());
3。使用java.util.PropertyResourceBundle類的構造函數
示例: InputStream in = new BufferedInputStream(new FileInputStream(name));
ResourceBundle rb = new PropertyResourceBundle(in);
4。使用class變量的getResourceAsStream()方法
示例: InputStream in = JProperties.class.getResourceAsStream(name);
Properties p = new Properties();
p.load(in);
5。使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法
示例: InputStream in = JProperties.class.getClassLoader().getResourceAsStream(name);
Properties p = new Properties();
p.load(in);
6。使用java.lang.ClassLoader類的getSystemResourceAsStream()靜態方法
示例: InputStream in = ClassLoader.getSystemResourceAsStream(name);
Properties p = new Properties();
p.load(in);
補充
Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法
示例:InputStream in = context.getResourceAsStream(path);
Properties p = new Properties();
p.load(in);
public class PropertyUtils extends PropertyPlaceholderConfigurer {
public static final String MD5_KEY = "md5_key";
private Properties properties;
public String getProperty(String key) throws Exception{
if(properties == null){
properties = mergeProperties();
}
return properties.getProperty(key);
}
private Map<String, String> sysProperties;
public Map<String, String> getSysProperties(){
return sysProperties;
}
public void setSysProperties(Map<String, String> sysProperties){
Set<String> keySet = sysProperties.keySet();
for(String key : keySet){
String value = sysProperties.get(key);
System.setProperty(key, value);
}
}
public static void main(String args[]) throws Exception{
/**
* <bean id="propertyConfigurer" class="com.grabweb.util.PropertyUtils">
* <property name="locations" value="web.properties" />
* </bean>
* md5_key = SBXT6XT2ZT9MNNC1WP7EDE86K1R6KNJDMWMRK5AOHS7CI7AALDHB9DGBF786WAIK
*/
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
PropertyUtils pu = (PropertyUtils)context.getBean("propertyConfigurer");
String result = pu.getProperty(PropertyUtils.MD5_KEY);
System.out.println(result);
}
}