加载src下的配置文件

来源:互联网 发布:qq邮箱mac版下载 编辑:程序博客网 时间:2024/06/05 11:29

为了避免硬编码,现在编程很多地方都写成配置文件,这时候就需要我们进行对配置文件的读取,废话不多说,直接贴代码:

1.首先建一个db.properties的文件(放在src文件夹下)

DriverClassName=com.jdbc.mysql.DriverUrl=jdbc\:mysql\://localhsot\:3306/testUserName=rootPassword=admin

2.编码测试

package com.easyteam.yc;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.InputStream;import java.util.Properties;import org.junit.Test;/** * <p>title Demo * <p>Description: 加载配置文件<P> * <P>Company:com.easyteam.cn * @author yc * @date 2016-6-28 下午04:35:05 * */public class Demo {//方式一和方式二的主要区别就是文件前面是否加上/@Testpublic void fun() throws Exception{Properties pro=new Properties();//生成Properties对象//方式一://InputStream inStream=Demo.class.getResourceAsStream("/db.properties");//将配置文件变成输入流对象//方式二:InputStream inStream=Demo.class.getClassLoader().getResourceAsStream("db.properties");pro.load(inStream);//加载配置文件String DriverClassName=pro.getProperty("DriverClassName");//通过键找到对应的值System.out.println(DriverClassName);}}

如果改配置文件放在src的某个包中,那么在配置文件前面加上特定的报名即可,这时候包名之间不再是点,而是斜杠。

0 0
原创粉丝点击