캠핑과 개발


java.util.Properties 파일 사용 예제

package kr.pe.anaconda.test.io.file;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author diem
 * 
 */
public class PropertiesSample {

	private static String defaultPropertiesPath = "c:\\example.properties";

	public static String getDefaultPropertiesPath() {
		return defaultPropertiesPath;
	}

	public static void setDefaultPropertiesPath(String defaultPropertiesPath) {
		PropertiesSample.defaultPropertiesPath = defaultPropertiesPath;
	}

	public static String getKey(String key) throws Exception {

		// ClassLoader.getResourceAsStream("some/pkg/resource.properties");
		// Class.getResourceAsStream("/some/pkg/resource.properties");
		// ResourceBundle.getBundle("some.pkg.resource");
		String value = null;
		InputStream is = new FileInputStream(defaultPropertiesPath);
		Properties p = null;
		try {
			p = new Properties();
			p.load(is);
			value = p.getProperty(key);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {is.close();} catch (IOException e) {}
		}
		return value;
	}

	/**
	 * 프로퍼티 파일에 사용자 값을 넣는다.
	 */
	public static void putPropertie(Map paramMap)
			throws FileNotFoundException, IOException {
		// 프로퍼티 파일 경로 key
		String propertiesKey = "properties.file.path";
		Properties proper = null;
		FileOutputStream output = null;
		try {
			String comment = paramMap.get("properties.comment");
			// 사용자가 프로퍼티 파일 경로를 넘기지 않을 경우 default properties로 셋팅하다.
			if (!paramMap.containsKey(propertiesKey)) {
				paramMap.put(propertiesKey, defaultPropertiesPath);
			}
			output = new FileOutputStream(paramMap.get(propertiesKey));
			// paramMap.remove(propertiesKey);
			proper = new Properties();
			proper.putAll(paramMap);
			proper.store(output, comment);
		} catch (FileNotFoundException fnfe) {
			throw new FileNotFoundException("properties 파일을 찾을수 없습니다.");
		} catch (IOException ioe) {
			throw new IOException("putPropertie Exception!", ioe);
		} finally {
			try {
				output.close();
			} catch (IOException e) {
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		Map paramMap = new HashMap();
		paramMap.put("properties.file.path", "c:\\example12.properties");
		paramMap.put("name", "홍길동");
		paramMap.put("age", "31");
		paramMap.put("phone", "0111234567");
		PropertiesSample.putPropertie(paramMap);

		PropertiesSample.setDefaultPropertiesPath(paramMap
				.get("properties.file.path"));

		System.out.println(PropertiesSample.getDefaultPropertiesPath());
		System.out.println(PropertiesSample.getKey("name"));
	}
}