详述properties文件

一般来说一个项目打包之后便不能修改类中属性,但是一些信息有必要多次修改,例如jdbc连接数据库时在DriverManager.getConnection(url, user, password)中的url,user,password经常需要修改,因此我们需要一个配置文件专门配置这些信息。
properties文件是以.properties结尾的配置文件,这种文件以key=value格式存储内容,Java中可以直接使用Properties类来读取这个文件。我们可以将jdbc连接数据库所需要的信息存储在properties文件中。
例如:

url=jdbc:mysql://127.0.0.1:3306/test
user_name=root
password=

如何使用:

public class PropertiesUtil {

	private static Properties properties = new Properties();
	static {
		InputStream inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream("db.properties");
		try {
			properties.load(inputStream);//将properties文件中的每对key=value变为map集合中的键值对
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static String getValue(String key) {
		return properties.getProperty(key);
	}
	public static void main(String[] args) {
		
		String url = PropertiesUtil.getValue("url");
		String user_name = PropertiesUtil.getValue("user_name");
		String password = PropertiesUtil.getValue("password");
		System.out.println(url+","+user_name+","+password);
	}
}

执行结果:
在这里插入图片描述
因为此处我的数据库密码为空故输出为空。
而此时获取连接方法变为:

public static Connection getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = PropertiesUtil.getValue("url");
			String userName = PropertiesUtil.getValue("user_name");
			String password = PropertiesUtil.getValue("password");
			return DriverManager.getConnection(url,userName,password);	
		} catch (Exception e) {
			logger.debug(e.getMessage(),e);
		}
		return null;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值