java读取properties文档
- 参考:
java如何读取.properties文件 http://fangguanhong.iteye.com/blog/1188521
两种方法:
第一种:用jdk自带的类
第二种:用commons-configuration.jar为我们提供的方法
参考这个方法http://javamy.iteye.com/blog/252619
第一种:用jdk自带的类
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.Properties;
- import org.apache.log4j.Logger;
- /**
- * 常量配置类,从指定文件读取常量
- */
- public class ConfigurableContants {
- private static final Logger logger = Logger.getLogger(ConfigurableContants.class);
- public static Properties properties = new Properties();
- public static void init(String propertyFileName) {
- InputStream in = null;
- try {
- //InputStream inStream =new FileInputStream("sys.properties");
- // this.getClass().getResourceAsStream("/sys.properties");
- //Test.class.getClassLoader().getResourceAsStream("sys.properties")
- in = ConfigurableContants.class.getResourceAsStream(propertyFileName);
- if (in != null)
- properties.load(in);
- } catch (IOException e) {
- logger.error("load " + propertyFileName + " into Contants error");
- } finally {
- if (in != null) {
- try {
- in.close();
- } catch (IOException e) {
- e.printStackTrace(e);
- }
- }
- }
- }
- public static String getProperty(String key, String defaultValue) {
- return properties.getProperty(key, defaultValue);
- }
- public static Object setProperty(String key, String Value) {
- return properties.setProperty(key, Value);
- }
- }
第二种:用commons-configuration.jar为我们提供的方法
参考这个方法http://javamy.iteye.com/blog/252619