Properties文件的读取方式

           近段时间工作中涉及到了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);
	}
}

    总结:读取的方式除以上几种外还有很多种方式,选择简便快捷适合自己的即可。


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值