很多时候,一些参数都不能在程序里面“写死”,因为参数一旦需要变更,那么程序也需要跟着变动。所以,我们必须将这些参数写在一个配置 文件中,以便后期的修改。
下面,就以连接数据库为例,讲一下如何写配置文件(xxx.properties),这是一个继承了HashTable的类。
连接数据库我们需要几个参数:
1、forname:标识你用的是哪种类型的数据库,如:MySQL、Oracle
在这个例子中我们用的是MySQL,如果后期改成了Oracle,只需要将这个配置文件的forName修改。
forName=com.mysql.jdbc.Driver
//com.公司名.项目名.类名
2、url:资源路径
url =jdbc:mysql://localhost:3306/usermanagersystem
3、username:用户名
username =xxx
4、password:密码
注意:在写配置文件的时候 key:value,不能加“”。之前在写的时候写了双引号就一直连不上。
写完配置文件后,我们就需要去读取配置文件,有两种方式。
方式一:
用当前类来获得类加载驱动
InputStream in =JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
//当前类为JdbcUtil
方式二:
直接用classLoader
InputStream in = ClassLoader.getSystemResourceAsStream("aa.txt");
下面是数据库获取连接的代码:
static
{
try
{
//第一步:创建一个Properties
Properties properties = new Properties();
//第二步:获取流 用class进行类加载 注意:这个是getResourceAsStream
InputStream in =JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
//装载文件
properties.load(in);
forName = properties.getProperty("forName");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
//不需要每次都加载一次驱动
Class.forName(forName);
} catch (Exception e) {
e.printStackTrace();
}
}
因为我们只希望驱动只加载一次,所以就把它写在了静态代码块中。