Properties读取小结

一、Java程序中读取properties文件

加载的工具类: 

import java.io.File;  
import java.io.FileOutputStream;  
import java.io.InputStream;  
import java.util.Properties;  
  
import org.apache.commons.logging.Log;  
import org.apache.commons.logging.LogFactory;  
  
/** 
 * Properties工具类 
 * @author happyqing 
 * @since 2014.6.6 
 */  
public class PropertiesUtil {  
    private static final Log log = LogFactory.getLog(PropertiesUtil.class);   
    private static Properties env = new Properties();  
      
    static {  
        try {  
            //PropertiesHelper.class.getResourceAsStream("env.properties"); // /com/cici/conf/env.properties  
            //ClassLoader.getSystemResourceAsStream("env.properties");  
            InputStream is = PropertiesUtil.class.getClassLoader().getResourceAsStream("env.properties");  
            env.load(is);  
            is.close();  
        } catch (Exception e) {  
            log.error(e);  
        }  
    }  
      
    /** 
     * 取属性值 
     * @param key 
     * @return  
     */  
    public static String getProperty(String key){  
        return env.getProperty(key);  
    }  
      
    /** 
     * 设置属性值 
     * @param key 
     * @param value  
     */  
    public static void setProperty(String key, String value){  
        try{  
            File file = new File(PropertiesUtil.class.getClassLoader().getResource(".").getPath()+File.separator+"env.properties");  
            FileOutputStream outStream = new FileOutputStream(file);  
            env.setProperty(key, value);  
            //写入properties文件  
            env.store(outStream, null);  
        } catch (Exception ex) {  
            log.error(ex);  
        }  
    }  
      
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
        System.out.println(PropertiesUtil.getProperty("txtLength"));  
        //System.out.println(PropertiesUtil.class.getClassLoader().getResource(".").getPath());  
    }  
}  

  频繁的配置文件读取与操作,推荐apache commons大家庭的成员:commons-configuration

文件结构目录如图所示:

  其中,config2为与src同级的sourec folder,c.properties位于src根目录,b.properties位于src/config1 folder下

a.properties位于cn.package1包下。所有结果均已成功测试,测试环境为Myeclipse2016+JDK8

   其实以下也就是程序路径的区分

  1.读取a.properties:

 1 package cn.package1;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.util.Properties;
 6 
 7 import org.junit.Test;
 8 
 9 public class Demo01 {
10     @Test
11     public void fun1() throws IOException{
12         InputStream in1 = Demo01.class.getClassLoader()
13                 .getResourceAsStream("cn/package1/a.properties");
14         Properties props = new Properties();
15         props.load(in1);
16         String value1 = props.getProperty("name");
17         System.out.println(value1);
18     }
19 }

(输入流的处理以及关闭可以改进)

  2.读取b.properties:

  (重复代码已经省略!)

1 InputStream in1 = Demo01.class.getClassLoader()
2                 .getResourceAsStream("config1/b.properties");

  3.读取c.properties:

1 InputStream in1 = Demo01.class.getClassLoader()
2                 .getResourceAsStream("c.properties");

  4.读取d.properties:

InputStream in1 = Demo01.class.getClassLoader()
                .getResourceAsStream("d.properties");

二、Spring项目中读取properties

   总之就是,一定要加载到properties文件然后才能读取(xml文件读取或者java代码读取),至于加载的方式,可以是下面的直接使用context标签进行加载,例如使用classpath:*.properties(见下文配置文件),或者使用文末随笔中提到的使用spring的bean来进行加载!

   1.配置文件中使用——使用${}取值即可

  spring配置文件如何读取属性配置文件:

     <!-- 加载配置属性文件 -->
      <context:property-placeholder ignore-unresolvable="true" location="classpath:jeesite.properties" />
      <!-- 基本属性 url、user、password -->
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />

   springMVC中进行配置:

  <!-- 加载配置属性文件 -->
    <context:property-placeholder ignore-unresolvable="true" location="classpath:jeesite.properties" />
    
    <!-- 使用Annotation自动注册Bean,只扫描@Controller -->
    <context:component-scan base-package="com.thinkgem.jeesite" use-default-filters="false"><!-- base-package 如果多个,用“,”分隔 -->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

  // 必须注意,不使用默认的过滤器!

  2.Java代码中取值——使用@Value读取

/**
     * 管理基础路径
     */
    @Value("${adminPath}")
    protected String adminPath;
    
    /**
     * 前端基础路径
     */
    @Value("${frontPath}")
    protected String frontPath;
    
    /**
     * 前端URL后缀
     */
    @Value("${urlSuffix}")
    protected String urlSuffix;

   // 像这里我们可以直接把它做成一个父类,这样每个类只需要继承父类便可使用此变量,而无须重复使用每个类的局部变量

  请谨记很多东西没必要写死的应该写在配置文件中,比如服务器的地址,数据库的密码等,不应该在程序中写死,而应该归配置文件管理!

   spring中读取配置文件也可以参见http://www.cnblogs.com/Gyoung/p/5507063.html

原文地址:https://www.cnblogs.com/jiangbei/p/6665322.html