Java 开发技巧

一 读取配置文件

1 Properties读取配置文件

  编写配置文件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);

    }

2 ResourceBundle读取配置文件 

  读取的配置文件格式是 配置文件.properties格式, 扩展名 .properties 省略。就像对于类可以省略掉 .class扩展名一样,资源文件必须位于指定包的路径之下(位于所指定的classpath中)  

如果是Web项目,不写包路径可以,此时将资源文件放在WEB-INFclasses目录下就可以。

ResourceBundle resourceBunlde =ResourceBundle.getBundle("config");
tring key = resourceBunlde.getString("jdbc_password");
System.out.println(key);    
原文地址:https://www.cnblogs.com/wangshuo1/p/5772691.html