近段时间工作中涉及到了Properties文件的读取方式,在总结几种本人认为比较简便的方式以作记录:
(一)使用java.util.Properties读取
public String getProperties(String url,String key) throws IOException {
// ClassLoader()和URLClassLoader()区别:ClassLoader()只能查找src目录下的文件,而URLClassLoader()则能查找任意目录下的文件。
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(url);
Properties prop = new Properties();
try{
prop.load(inputStream);
}catch (IOException ioE){
ioE.printStackTrace();
}finally{
inputStream.close();
}
String property = prop.getProperty(key);
return property;
}
(二)使用Spring中的环境抽象Environment及注解@PropertySource
/**
* @author : ShiLei
* @time :2018年1月17日 上午11:34:27
* @introduction : properties文件读取
*/
@Controller
@PropertySource({"classpath:properties/excel.properties"})
@RequestMapping("zwDataTempletController")
public class ZWDataTempletController {
@Value("${key}")
private Environment env;
@RequestMapping("downloadExcelTemplet")
@ResponseBody
public MyResult downloadExcelTemplet(String key) throws Exception{
String path="";
if (!"".equals(key)) {
path=env.getProperty(key);
return MyResult.ok(path);
}
return MyResult.error("参数传入有误!");
}
}
(三)使用Spring中的注解@Value
在使用前需要在spring.xml文件中配置properties文件的读取位置:
<bean id="appProperty" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<array>
<value>classpath:properties/excel.properties</value>
</array>
</property>
</bean>
其次再进行该注解的使用:
/**
* @author : ShiLei
* @time :2018年1月17日 上午11:34:27
* @introduction : properties文件读取
*/
@Controller
@RequestMapping("dataTempletController")
public class DataTempletController {
@Value("${key}")
private String url;
@RequestMapping("downloadExcelTemplet")
@ResponseBody
public MyResult downloadExcelTemplet() throws Exception{
return MyResult.ok(url);
}
}
总结:读取的方式除以上几种外还有很多种方式,选择简便快捷适合自己的即可。