您的位置:首页 > 运维架构

在jdbc中使用properites文件进行使用

2016-06-01 16:17 225 查看
首先先在源代码中创建一个properites文件

db_url=jdbc\:mysql\://localhost\:3306/db_friend
db_user=root
db_password=
db_driver=com.mysql.jdbc.Driver


 然后再在你自己的代码中添加如下代码

private static String db_driver="";
private    static String db_url="";
private static String db_user="";
private static String db_password="";
static{
Locale locale=Locale.getDefault();//获取国家
ResourceBundle bandle=ResourceBundle.getBundle("cn/lonecloud/demo/jdbc",locale);//获取这个文件的内容第一个参数为相对这个文件的路径
db_driver=bandle.getString("db_driver");
db_url=bandle.getString("db_url");
db_user=bandle.getString("db_user");
db_password=bandle.getString("db_password");

}


如果你设置的properties文件为只读文件则使用这种方法

import java.io.InputStream;
import java.util.Properties;

public class demo {

public static void main(String[] args) {
// TODO Auto-generated method stub
Properties properties=new Properties();//创建Properties类
InputStream in=demo.class.getResourceAsStream("jdbc.properties");//获取文件流
try {
properties.load(in);//将文件流导入properties中
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(properties.getProperty("db_url"));//获取键值
}

}


  利用这个的第三种方法

import java.io.InputStream;
import java.util.Properties;

public class demo {

public static void main(String[] args) {
// TODO Auto-generated method stub
Properties properties=new Properties();//创建Properties类
InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties");//获取文件流
try {
properties.load(in);//将文件流导入properties中
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(properties.getProperty("db_url"));//获取键值
}

}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: