您的位置:首页 > 编程语言 > Java开发

java中如何读取外部配置文件中的内容到代码中

2019-02-22 15:18 381 查看

java中的配置文件如何读取到代码中去呢

以下我就以properties配置文件为例 :
如我有一个配置文件,名为DBConfig.properties,他其中的内容和位置如下:

jdbcDriver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/mybatis
userName=root
password=root
initCount=10
stepSize=4
poolMaxSize=150

位置在src目录底下

那么我们只需要在java中写这个方法,即可拿到配置文件中相应参数的值,配置文件可能提高代码的可复用性以及可读性,所以配置文件是代码中必不可少的一个环节,希望能对你有用。

private void init(){
//读取外部配置参数
InputStream in=this.getClass().getClassLoader().getResourceAsStream("DBConfig.properties");
Properties properties=new Properties();
try {
//将信息有key-value形式化properties
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
}
jdbcDriver=properties.getProperty("jdbcDriver");
userName=properties.getProperty("userName");
jdbcUrl=properties.getProperty("jdbcUrl");
password=properties.getProperty("password");
initCount=Integer.valueOf(properties.getProperty("initCount"));
stepSize=Integer.valueOf(properties.getProperty("stepSize"));
poolMaxSize=Integer.valueOf(properties.getProperty("poolMaxSize"));
}

越努力,越幸运。不断学习,不断成长!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: