首先先在源代码中创建一个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"));//获取键值
}
}