一、properties文件
Properties文件是java中很常用的一种配置文件,文件后缀为“.properties”,属文本文件,文件的内容格式是“键=值”的格式,可以用“#”作为注释
java应用通过JDBC连接数据库时,可以把数据库的配置写在配置文件 jdbc.properties
二、读取配置文件数据
1.使用properties类获取配置文件数据
1.1实例化properties类(java.util.Properties)
Properties prop = new Properties();
1.2、利用Properties中的load()方法加载配置文件
使用类的反射来加载配置文件并且要写入配置文件的正确的路径(这里使用配置文件的路径在src的根目录下,相应的Java文件在src中其中一个包中)
prop.load(DBUtil.class.getResourceAsStream("/jdbc.properties"));
1.3、利用Properties中的getProperty(“名”)获取配置文件中的值
String DRIVERNAME = prop.getProperty("DRIVER");
2…通过java.util.ResourceBundle类来读取
通过ResourceBundle.getBundle()静态方法来获取(ResourceBundle是一个抽象类),这种方式来获取properties属性文件不需要加.properties后缀名,只需要文件名即可,比使用Properties要方便一些
public static String getValue(String key){
ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
return bundle.getString(key);
}