zoukankan      html  css  js  c++  java
  • 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);    
  • 相关阅读:
    【程序15】成绩>=90分用A表示,60-89分用B表示, 60分以下用C表示。
    【程序13】打印出所有的“水仙花数”,运算符和表达式
    cacti安装
    lamp安装
    虚拟机克隆之后网络重启失败
    Linux 标准输入输出、重定向
    /etc/crontab和crontab -e的区别
    nginx安装
    【程序11】有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,问每个月的兔子总数为多少?
    【程序9】输出国际象棋棋盘
  • 原文地址:https://www.cnblogs.com/wangshuo1/p/5772691.html
Copyright © 2011-2022 走看看