码迷,mamicode.com
首页 > 编程语言 > 详细

Java 开发技巧

时间:2016-08-15 14:13:46      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

1 加载配置文件

  编写配置文件config.properties放在普通java工程的src目录(如果是maven工程就放在工程的src/main/resources)目录下

config.properties

hibernate.dialect=org.hibernate.dialect.OracleDialect
driverClassName=oracle.jdbc.driver.OracleDriver
jdbc_url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
jdbc_username=wang
jdbc_password=123456

技术分享

PropertiesTool.java

public class PropertiesTool {
    private Properties props = null;

    public void loadProp(String configPath) {
        InputStream inputStream = Object.class.getResourceAsStream(configPath);
        props = new Properties();
        try {
            props.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("couldn‘t find properties file,please check it.");
        }
    }

    public String readValue(String key) {
        String value = null;
        if (null != props) {
            value = props.getProperty(key);
        }
        return value;
    }

}

运行测试文件

1 读取src根文件下的config.properties

public static void main(String[] args) {
        PropertiesTool propTool = new PropertiesTool();
        String configPath = "/config.properties";
        propTool.loadProp(configPath);
        String value = propTool.readValue("hibernate.dialect");
        System.out.println("value=" + value);

}

2 读取 src根目录下com/xinping/service目录下的config.properties

public static void main(String[] args) {
        PropertiesTool propTool = new PropertiesTool();
        String configPath = "/com/xinping/service/config.properties";
        propTool.loadProp(configPath);
        String value = propTool.readValue("hibernate.dialect");
        System.out.println("value=" + value);

    }

 

  

 

Java 开发技巧

标签:

原文地址:http://www.cnblogs.com/wangshuo1/p/5772691.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!