Java读取.properties文件

在java-web项目的开发中,经常读取properties的配置文件。但是对于properties的路径问题很是疑惑,本次总结,是将文件放到src目录下。
这样省了好多事情。写到这里,是为了以后在遇到这种事情,就直接copy了,毕竟作为程序员都是比较“懒”的。

直接上代码吧

import java.io.IOException;
import java.util.Properties;

/**
 * 读取配置文件信息
 * @ClassName:  ReadProperties   
 * @Description:TODO(这里用一句话描述这个类的作用)   
 * @author LiYonghui
 * @date Jul 21, 2017 2:48:01 PM
 */
public class ReadProperties {  
    private static Properties initPrperties(String filePath) throws IOException{
        Properties props = null;
        if(props==null){
            props = new Properties(); 
            props.load(ReadProperties.class.getClassLoader().getResourceAsStream(filePath));
        }
        return props;
    }

    /**
     * @throws IOException 
     * 读取信息
     * @Title: getStringValue   
     * @Description: TODO(这里用一句话描述这个方法的作用)   
     * @param: @param props
     * @param: @param key
     * @param: @return  
     * @author LiYonghui    
     * @date Jul 21, 2017 2:48:43 PM
     * @return: String      
     * @throws
     */
    public static String getValue(String filePath,String key) throws IOException{
        Properties props = initPrperties(filePath);
        return props.getProperty(key);
    }

   public static void main(String[] args) throws Exception{  
        //String filename = "com/lyh/xml/read.properties";  
        String filename = "toEmailConfig.properties"; 
        System.out.println(getValue(filename,"emails")); 

    } 
} 

上man方法中toEmailConfig.properties是放在src目录下的。并且里面有个emails为名称的一行字符串

emails=liyonghui1023@outlook.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值