反射机制-属性配置文件-ResourceBundle资源绑定器获取配置文件
通过资源绑定器获取配置文件:
java.util包下提供了一个资源绑定器,便于获取属性配置文件中的内容。
使用以下这种方式的时候,属性配置文件xxx.properties必须放到类路径下src。
属性配置文件:直接在src类路径下创建
mport java.util.ResourceBundle; public class ResourceBundleTest { public static void main ( String[] args ) { ResourceBundle bundle = ResourceBundle.getBundle("jdbc");//文件名不可以加上:properties String url = bundle.getString("jdbc_url"); String driver = bundle.getString("jdbc_driver"); String user = bundle.getString("jdbc_user"); String password = bundle.getString("jdbc_password"); System.out.println("mysql驱动:"+driver); System.out.println("mysql解析地址:"+url); System.out.println("mysql用户名:"+user); System.out.println("mysql密码:"+password); } }
属性配置文件更换包以后的类路径需要一起写道资源绑定器中:
以类路径的方式去找到该属性配置文件;属性配置文件不能添加拓展名
ResourceBundle bundle = ResourceBundle.getBundle("com/xzit/platfrom/test/jdbc");//文件名不能加上:properties
IO+properties:直接以流的形式返回属性配置文件:
import java.io.FileReader; import java.io.InputStream; import java.util.Properties; public class IoPropertiesTest { public static void main(String[] args) throws Exception{ // 直接以流的形式返回。 InputStream reader = Thread.currentThread().getContextClassLoader() .getResourceAsStream("classinfo2.properties"); Properties pro = new Properties(); pro.load(reader); reader.close(); // 通过key获取value String className = pro.getProperty("className"); System.out.println(className); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了