Java读取.properties文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Allen202/article/details/76653644

在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为名称的一行字符串

[email protected]

猜你喜欢

转载自blog.csdn.net/Allen202/article/details/76653644