这里我们给出两种获取配置文件(properties)读取,显然JDK为我们提供的ResourceBundle类,获取配置文件信息要方便的多
1.流方式与持久化类
private static void readContext() {
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties"); //获取配置文件信息,返回一个流对象
Properties props = new Properties();
try {
props.load(is);
driver = props.getProperty("driver");
url = props.getProperty("url");
username = props.getProperty("username");
password = props.getProperty("password");
} catch (IOException e) {
throw new RuntimeException(e + "文件解读失败!");
}
}
2.ResourceBundle类
private static void readContext() {
ResourceBundle rb = ResourceBundle.getBundle("com.java.jdbc.db"); //获取配置文件
driver = rb.getString("driver");
url = rb.getString("url");
username = rb.getString("username");
password = rb.getString("password");
}