/*
 * $Id: PropertiesUtil.java 30 2014-07-03 08:57:36Z guyejun $
 */

package com.fr.tx.common.util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

/**
 * 
 * Properties文件处理
 * 
 */
public class PropertiesUtil {

	/**
	 * Properties
	 */
	private Properties propertie;

	/**
	 * 流
	 */
	private InputStream input;

	/**
	 * 流
	 */
	private OutputStream output;
	/**
	 * PropertUtil構造体の初期化
	 */
	public PropertiesUtil() {

		propertie = new Properties();
	}

	/**
	 * PropertUtil構造体の初期化
	 * 
	 * @param fileName
	 *            ファイル名称
	 */
	public PropertiesUtil(String fileName) {

		propertie = new Properties();
		try {
			input = this.getClass().getClassLoader().getResourceAsStream(fileName);
			
			propertie.load(input);

			input.close();
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 取値
	 * 
	 * @param key
	 *            キー
	 * @return 　値
	 */
	public String getValue(String key) {

		if (propertie.containsKey(key)) {
			String value = propertie.getProperty(key);
			return value;
		} else {
			return "";
		}

	}

	/**
	 * 取値
	 * 
	 * @param fileName
	 *            ファイル名称
	 * @param key
	 *            キー
	 * @return 値
	 */
	public String getValue(String fileName, String key) {

		String value = "";
		try {
			input = this.getClass().getClassLoader()
					.getResourceAsStream(fileName);
			propertie.load(input);
			input.close();
			if (propertie.containsKey(key)) {
				value = propertie.getProperty(key);
				return value;
			} else {
				return value;
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return "";
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		} catch (Exception ex) {
			ex.printStackTrace();
			return "";
		}
	}

	/**
	 * 设置値
	 * 
	 * @param fileName
	 *            文件名称
	 * @param key
	 *            键
	 * @param value
	 *            値
	 * 
	 */
	public void setValue(String fileName, String key, String value) {

		try {

			output = new FileOutputStream(this.getClass().getResource("/" + fileName).getPath());
			propertie.setProperty(key, value);
			propertie.store(output, "last update");

			output.close();
			input.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();

		} catch (IOException e) {
			e.printStackTrace();

		} catch (Exception ex) {
			ex.printStackTrace();

		}
	}

	/**
	 * propertieファイルのクリア
	 */
	public void clear() {

		propertie.clear();
	}
}
