1.原因
为了更方便的获取.properties文件中的内容
2.方法
通过反射加载文件路径,获取文件流,然后读取流信息,获取指定数据
Properties properties;
1.
/** * 获取当前类文件编译之后存储路径 * /D:/workSpace/mineSvnWorkSpace/demo/demo_core/demo_back/target/classes/com/cll/yl/demo/back/common/util/ */ String currentPath = this.getClass().getResource("").getPath(); /** * 通过类加载器,获取项目编译过后根目录 * /D:/workSpace/mineSvnWorkSpace/demo/demo_core/demo_back/target/classes/ */ String rootPath = this.getClass().getClassLoader().getResource("").getPath(); if (StringUtils.isNotEmpty(rootPath)) { String filePath = rootPath + fileName; FileInputStream fileInputStream = new FileInputStream(filePath); InputStream inputStream = new BufferedInputStream(fileInputStream); // 解决获取配置文件中中文乱码问题 InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); Properties properties = new Properties(); properties.load(inputStreamReader); properties.getProperty(keyName); }
2.
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileName); if (null != inputStream) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); properties = new Properties(); properties.load(inputStreamReader); properties.getProperty(keyName); }
3.如果使用了Spring框架,可以将*.properties的属性文件加载到Spring容器中,然后使用注解读取配置文件中的内容
<!-- 引入参数配置文件 --> <bean id="propertyConfigure" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:system.properties</value> <value>classpath:jdbc.properties</value> </list> </property> </bean>
system.properties文件中只有一行数据
dialect=MySQL
在需要使用的地方,进行如下操作
@Value("${dialect}")
private String dialect;