1.Properties如何创建?
eclipse中:new->file->输入名称
2.Properties创建范例。
JDK中查询Properties可以看出,Properties继承Hashtable,所以Properties的格式也是键对应值。
- driverClassName:驱动
- url:数据库位置
- username:数据库账户名
- password:我的数据库密码
3.如何调用配置文件Properties?
我之前在工具类的封装中使用了静态代码块来封装驱动的加载,现在也在里边引入配置文件Properties。为了随着类的加载获取到我的数据库地址、账户、密码,其实就是怎么使用properties。
//加载驱动,在程序启动的时候就被加载且只执行一次
static{
try {
Properties properties = new Properties();//创建配置文件对象
//通过类获取流的对象
InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
properties.load(in);//通过字节输入流in读取里边的键值对
driver = properties.getProperty("driverClassName");//获取键对应的值
url = properties.getProperty("url"); //获取键url对应的值
username = properties.getProperty("username"); //获取键username对应的值
password = properties.getProperty("password"); //获取键password对应的值
Class.forName(driver); //加载驱动
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
解析一下JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
JDBCUtils:是我的工具类名称
JDBCUtils.class:是这个类的.class文件
.getClssLoader:是类加载器,为了解析这个JDBCUtils.class文件,JDBCUtils.class文件是在JVM中运行的,本地不能执行这个.class文件。随着Java程序的运行,.class文件会进入JVM中,而负责加载这个.class文件的部件就称为类加载器ClassLoader。
.getResourceAsStream:返回的是InputStream对象