java读取properties文件的方法
1:使用apache.commons组件。
需要使用jar包:commons-configuration-1.3.jar,commons-lang-2.3.jar,commons-collections.3.2.jar,commons-logging.jar
public class ConfigReader {
private static ConfigReader instance =new ConfigReader();
public static Configuration config ;
private ConfigReader(){
try{
config = new PropertiesConfiguration("test.properties");
}catch(NestableRuntimeException e2){
System.out.println("properties read error...");
}catch(ConfigurationException e3){
System.out.println("properties read error...");
}
}
public static ConfigReader getInstance(){
return instance ;
}
public static void main(String args[]) throws RemoteException, NestableRuntimeException, ConfigurationException {
System.out.println(ConfigReader.getInstance().config.getProperty("userid"));
}
}
2:使用java.util.ResourceBundle的getBundle()方法读取properties文件来获取值
public class ResourceBundleReader {
public final static Object initLock = new Object();
private final static String PROPERTIES_FILE_NAME = "property";
private static ResourceBundle bundle = null;
static {
try {
if (bundle == null) {
synchronized (initLock) {
if (bundle == null)
bundle = ResourceBundle.getBundle(PROPERTIES_FILE_NAME,Locale.CHINA);
}
}
} catch (Exception e) {
System.out.println("读取资源文件property_zh.properties失败!");
}
}
public static ResourceBundle getBundle() {
return bundle;
}
public static void setBundle(ResourceBundle bundle) {
bundle = bundle;
}
}
3:springMVC的话
<!-- 应用属性文件读入 org.springframework.beans.factory.config.PropertyPlaceholderConfigurer --><bean id="applicationProperties" value="true"/> <property name="locations"> <list><value>classpath:/jdbc.properties</value><value>classpath:/redis.properties</value> <value>classpath:/application.properties</value> </list> </property> </bean>
package com.kuke.core.util;import java.util.HashMap;import java.util.Map;import java.util.Properties;import org.springframework.beans.BeansException;import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;public class PropertiesHolder extends PropertyPlaceholderConfigurer {private static Map<String, Object> ctxPropertiesMap;@Overrideprotected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess,Properties props) throws BeansException {super.processProperties(beanFactoryToProcess, props);ctxPropertiesMap = new HashMap<String, Object>();for (Object key : props.keySet()) {String keyStr = key.toString();String value = props.getProperty(keyStr);ctxPropertiesMap.put(keyStr, value);}}public static Object getContextProperty(String name) {return ctxPropertiesMap.get(name);}}
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("ipConfig.properties"); Properties p = new Properties(); try { p.load(inputStream); } catch (IOException e1) { e1.printStackTrace(); } System.out.println("ip:"+p.getProperty("ip")+",port:"+p.getProperty("port"));