java 读取properties文件的3种方式

 

1.情景展示

  将要访问的接口地址等常用的配置添加到properties文件中,比直接写到java类中的好处在于:

  当我们需要修改相应配置时,直接修改properties文件,重启tomcat即可,避免了重新编译引用该配置的java文件,同时,也便于项目的维护。

方式一

  通过spring的工具类PropertiesLoaderUtils来实现对properties文件的解析

  所需jar包:spring的核心jar包,spring-core-版本号.jar

 1 import java.io.IOException;
 2 import java.util.HashMap;
 3 import java.util.Map;
 4 import java.util.Properties;
 5 import org.springframework.core.io.support.PropertiesLoaderUtils;
 6 
 7 /**
 8  * 借助spring读取Properties文件
 9  * @explain Spring 提供的 PropertiesLoaderUtils
10  * 允许您直接通过基于类路径的文件地址加载属性资源 最大的好处就是:实时加载配置文件,修改后立即生效,不必重启
11  * @author Marydon
12  * @creationTime 2018年5月23日上午9:58:59
13  * @version 1.0
14  * @since
15  * @email marydon20170307@163.com
16  */
17 public class PropertiesUtils {
18 
19     /**
20      * 读取properties文件
21      * @param fileName properties文件名及所在路径
22      * @explain 参数说明
23      * 1.传递的参数不是properties类型文件,不会报错,返回的是空Map;
24      * 2.传递的参数是根本不存在的properties文件,也不会报错,返回的是空Map;
25      * 3.传递的参数可以带路径,可以正常解析到
26      * @return
27      */
28     public static Map<String, String> readProperties(String fileName) {
29         Map<String, String> resultMap = new HashMap<String, String>();
30         try {
31             Properties props = PropertiesLoaderUtils.loadAllProperties(fileName);
32             for (Object key : props.keySet()) {
33                 resultMap.put(key.toString(), props.get(key).toString());
34             }
35         } catch (IOException e) {
36             e.printStackTrace();
37         }
38         return resultMap;
39     }
40 
41     /**
42      * @param args
43      */
44     public static void main(String[] args) {
45 //        Map map = readProperties("base/web/imageInfo/fileRootDirectories.properties");
46         Map map = readProperties("fileRootDirectories.properties");
47         for (Object key : map.keySet()) {
48             System.out.println(key.toString() + "=" + map.get(key).toString());
49         }
50         // 打印结果
51         // fileRootPath=uploadFiles
52     }
53 
54 }

  这种方式的缺点在于:

  每次调用都要重新解析对应的properties文件,所以,我们可以在项目启动的时候,就把该文件加载到内存中(一次加载解析,永久使用)。

20200902

方式二

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
 * properties文件工具类
 * @description
 * 在该类被加载的时候,它就会自动读取指定位置的配置文件内容并保存到静态属性中,高效且方便,一次加载,可多次使用
 * @author: Marydon
 * @date: 2020年07月13日 0013 16:04
 */
public class PropertyUtils_old {
   private static Logger logger = LoggerFactory.getLogger(PropertyUtils_old.  class );
   // 待解析的properties文件名称
   private static final String FILE_NAME =   "bill.properties" ;
   // 用于接收解析过properties文件
   private static Properties props;

   // 静态代码块:在该类被加载到内容中时,该代码块会执行
   static {
       // 静态代码块执行时将要执行的方法
       loadPropertiesFile();
   }

   synchronized static private void loadPropertiesFile() {
       logger.debug(  "开始加载properties文件内容......." );
       props =   new Properties();
       InputStream in =   null ;
       try {
           // 方式一:通过类加载器进行获取properties文件流(不用添加路径)
           in = PropertyUtils_old.  class .getClassLoader().getResourceAsStream(FILE_NAME);
           // 方式二:通过类进行获取properties文件流(需要加/)
           // in = PropertyUtils.class.getResourceAsStream("/bill.properties");
           props.load(in);
       }   catch (NullPointerException e) {
           logger.error(  "bill.properties文件未找到!" );
       }   catch (IOException e) {
           logger.error(  "出现IOException!" );
       }   finally {
           try {
               if (  null != in) {
                   in.close();
               }
           }   catch (IOException e) {
               logger.error(  "bill.properties文件流关闭出现异常" );
           }
       }
       logger.info(  "加载properties文件内容完成..........." );
       logger.info(  "properties文件内容:" + props);
   }

   /*
    * 获取properties文件中指定key的value
    * @date: 2020年07月13日 0013 16:17
    * @param: key
    * @return: java.lang.String
    */
   public static String getProperty(String key) {
       if (  null == props) {
           loadPropertiesFile();
       }
       return props.getProperty(key);
   }

   /*
    * 获取properties文件中指定key的value
    * @date: 2020年07月13日 0013 16:17
    * @param: key
    * @param: defaultValue
    * @return: java.lang.String
    */
   public static String getProperty(String key, String defaultValue) {
       if (  null == props) {
           loadPropertiesFile();
       }
       return props.getProperty(key, defaultValue);
   }
}

  测试

public static void main(String[] args) {
    System.out.println(getProperty(  "bill.czInterfaceAddress" ));
}

  方式一也可以按照方式二的形式,来达到一次加载,永久使用的效果。

20201106 

  如果properties文件中value的值为中文,取出来的值会是乱码,怎样解决?

  对乱码的值进行重新编码

ECNAME =   new String(resultMap.get(  "ecName" ).getBytes(  "ISO-8859-1" ),   "UTF-8" );

2023年9月11日10:51:41  

方式三

import java.util.Locale;
import java.util.ResourceBundle;
public class PropertiesUtil {
    private static final Logger log = Logger.getLogger(PropertiesUtil.class);
	
	private static ResourceBundle resource;
	// lis.properties
	private static final String FILE_SOURCE_LIS = "lis";
	
	static {
		resource = initProperty(FILE_SOURCE_LIS);
	}

	public static void setResource(String resourceFile) {
		resource = ResourceBundle.getBundle(resourceFile, Locale.SIMPLIFIED_CHINESE);
	}

	/**
	 * 根据key获取value
	 * @explain
	 * @param key 键(=号前面的名称)
	 * @return 值(=号后面的值)
	 * 如果key不存在,返回值为null
	 */
	public static String getProperty(String key) {
		String value;
		if (resource == null) {
			setResource(FILE_SOURCE_LIS);
		}
		try {
			value = resource.getString(key);
		} catch (Exception e) {
			log.error("不存在的属性key=" + key);
			value = null;
		}
		return value;
	}
	
	
	 /**
     * Property文件初始化
     * @explain
     * @param resourceFile 文件名
     * 只需传入文件名,不用传后缀名.properties
     * @attention
     * 1.必须是properties文件
     * 2.必须在src目录下
     * @return
     */
    synchronized private static ResourceBundle initProperty(String resourceFile) {
        try {
        	return ResourceBundle.getBundle(resourceFile, Locale.SIMPLIFIED_CHINESE);
        } catch (NullPointerException e) {
            log.error(resourceFile + " 文件在src目录下未找到");
            return null;
        }
        
	}
	
}

调用

public static void main(String[] args) {
	System.out.println(PropertiesUtil.getProperty("wj.task.log.path.preffix"));
}

 

 

posted @ 2018-06-07 08:31  Marydon  阅读(1093)  评论(0编辑  收藏  举报