properties是java中的一种配置文件,文件的内容是键-值的形式(key-value)。为了在java代码中使数据库的配置文件和代码分开,properties被引用了。文件名为:*.properties的形式。
在eclipse中经常新建一个sources文件,将其放入:
properties中我们主要放置jdbc的 四大参数:
我们只需要在java代码中读取文件中的参数值,从此java代码与数据库配置信息分开了。本文主要关注怎么读取properties。
private static Properties properties = new Properties(); static {
try { InputStream in = new FileInputStream("sourses/db.properties"); properties.load(in); Class.forName(properties.getProperty("driver")); } catch (FileNotFoundException e) {
e.printStackTrace(); } catch (IOException e) {
e.printStackTrace(); } catch (ClassNotFoundException e) {
e.printStackTrace(); }
}
private static Properties properties = new Properties(); static {
try { //InputStream in = new FileInputStream("sourses/db.properties"); InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"); properties.load(in); Class.forName(properties.getProperty("driver")); } catch (FileNotFoundException e) {
e.printStackTrace(); } catch (IOException e) {
e.printStackTrace(); } catch (ClassNotFoundException e) {
e.printStackTrace(); }
}
private static Properties properties = new Properties(); static {
try { //InputStream in = new FileInputStream("sourses/db.properties"); //InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"); InputStream in=JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties"); properties.load(in); Class.forName(properties.getProperty("driver")); } catch (FileNotFoundException e) {
e.printStackTrace(); } catch (IOException e) {
e.printStackTrace(); } catch (ClassNotFoundException e) {
e.printStackTrace(); }
}
