java读取 *.properties文件中所有对象

这里提供解析的辅助方法

package com.cms.util;



import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

	 
public final class MiscUtil {
 
    private static Map<String, String> configProperty = null;
    
	private static String configPropertyPath="classpath:jdbc.properties";
    
	 
	/**
	 * 从application.properties 文件中有key获取values
	 * @param key
	 * @return
	 */
	public static String getConfigByKey(String key) {
		if(isEmptyString(key)){ return null;		}
		try{
			if(configProperty==null){
				configProperty= MiscUtil.convertPropertiesFileToMap(configPropertyPath);
			}
		} catch(Exception e){
			//TODO add log info
			e.printStackTrace();
		}
		return configProperty.get(key).trim();
	}
	
	public static boolean isEmptyString(String value){
		return value==null?true:(value.trim().length()<1?true:false);
	}
	
  

	public static Map<String, String> convertPropertiesFileToMap(String path) throws Exception{
		InputStream input = null;
		Map<String,String> propertiesMap = null;
		try{
			if(path.toLowerCase().startsWith("classpath:")){
				String fileName = path.substring("classpath:".length());
				input = MiscUtil.class.getClassLoader().getResourceAsStream(fileName);
				if(input==null){
					path=MiscUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath();
					path=path.substring(0, path.lastIndexOf(File.separatorChar)+1)+fileName;
				}
			}
			if(input==null){
				input = new FileInputStream(path);
			}
			
			Properties properties = new Properties();
			properties.load(new InputStreamReader(input, "UTF-8"));
			propertiesMap = new HashMap<String,String>();			
			for(String name : properties.stringPropertyNames()){
				propertiesMap.put(name, properties.getProperty(name));
			}			
		}finally{
			if(input!=null){
				input.close();
			}
		}
		return propertiesMap;
	}
	
      
    
   
 
}


代码中 properties.load(new InputStreamReader(input, "UTF-8"));  这里是设置内容格式防止中文乱码的情况


下面给新手一点技巧 如果想要直接看到中文的话要把该文件的格式设置为utf-8 则可以看到中文


下图是 UNicode 码   该文件的格式为 iso-8859-1






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值