properties配置文件

开发中获得连接的四个参数(驱动,URL,用户名,密码)通常都存在配置文件中,方便后期维护,程序如果需要更换数据库,只需要修改配置文件即可。

通常情况下,我们习惯使用properties文件,此文件要求:

  1. 文件位置:任意,建议src下(非web应用)、classpath(web应用)
  2. 文件名:任意,扩展名为properties
  3. 文件内容:一行一组数据,格式“key=value”(不要有空格)
    1. key名自定义,如果是多个单词,习惯使用点分隔,例如:jdbc.driver
    2. Value值不支持中文,如果需要使用非英文字符,讲进行Unicode转换。

1、创建配置文件

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/student
user=root
password=root

2、加载配置文件:ResourceBundle对象

public class TextBundle {

	public static String driver;
	public static String url;
	public static String user;
	public static String password;
	
	static {
		ResourceBundle bundle = ResourceBundle.getBundle("db");
		driver = bundle.getString("driver");
		url = bundle.getString("url");
		user = bundle.getString("user");
		password = bundle.getString("password");
	}
	
	public static void main(String[] args) {
		System.out.println(driver);
	}
}

3、加载配置文件:Properties对象

public class TextBundle {

	public static String driver;
	public static String url;
	public static String user;
	public static String password;
	
	static {
		//1、通过当前类获取类加载器
		ClassLoader classloader = TextBundle.class.getClassLoader();
		//2、通过类加载器的方法获得一个输入流
		InputStream is = classloader.getResourceAsStream("db.properties");
		//3、创建一个properties对象
		Properties props = new Properties();
		//4、加载输入流
		try {
			props.load(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		//5、获得参数值
		driver = props.getProperty("driver");
		url = props.getProperty("url");
		user = props.getProperty("user");
		password = props.getProperty("password");
	}
	
	public static void main(String[] args) {
		System.out.println(driver);
	}
}

 

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值