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); }
时间: 2024-10-03 10:41:44