Java에서 properties파일 읽기

Java소스내에서 설정정보등이 등록된 properties파일을 읽어 프로그램에 적용하여야 할 경우가 있다.(예를들어 여기서는 mail.properties)

■ mail.properties, 파일위치는 classpath:/net/iotinfra/properties

mail.host=smtp.gmail.com
mail.port=587
mail.from=mirinae.maru@gmail.com
mail.username=mirinae.maru@gmail.com
mail.password=password

■ PropertiesUtil.java, mail.properties파일 내용을 읽는다.

import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;

public class PropertiesUtil {
	private static HashMap<String, Properties> propses;

	public static String get(String prop, String key){
		if(load(prop) == true){
			return propses.get(prop).getProperty(key);
		}
else{
			return "";
		}
	}
	
	/**
	 * Properties 가 적재되어 있는지 확인
	 * 적재되어 있지 않다면 적재함.
	 * properties 파일이 없을 경우 false return.
	 * 
	 * @param prop
	 * @return
	 */
	private static boolean load(String prop){
	
		// 초기화
		if(propses == null){ init(); }
		
		if(propses.containsKey(prop)){ return true; }
		else{
			try{
				StringBuilder path = new StringBuilder();
				path.append("net/iotinfra/properties/")
					.append(prop)
					.append(".properties");

			    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path.toString());
			    Properties props = new Properties();
			    props.load(is);
	
			    propses.put(prop, props);
			    
			    is.close();

			    return true;			    
			}
			catch(Exception e){
				logger.error(StringUtils.getLogText(e));
				return false;
			}
		}
	}
	
	/**
	 * 초기화  
	 */
	private static void init(){
		propses = new HashMap<String, Properties>();
	}
}

■ 소스 내에서 mail.properties파일 정보를 읽는 코드, 첫번재 인자는 파일명이고 두번째 인자는 원하는 정보의 key, value중에서 key 값이다.

String from = PropertiesUtil.get("mail", "mail.from");