java通過虛擬機設置參數的方式動態獲取當前項目的絕對路徑

public final static String RUNTIME_HOME = System.getProperty("RUNTIME_HOME");
	
	protected volatile boolean reload = false;

	protected final String CONFIG_FILE;
	protected final Properties prop = new Properties();
	
	private static CBECConfigFile instance = new CBECConfigFile();
	
	public static CBECConfigFile getInstance(){
		return instance;
	}
	
	private CBECConfigFile(){
		this(RUNTIME_HOME + "/config/" + "cbec-config.properties");
	}
	
	protected CBECConfigFile(String configFile){
		CONFIG_FILE = configFile;
		this.init();
	}
	
	/**
	 * 加載配置文件到內存中
	 */
	private void init() {
		InputStream is = null;
		try {
			is = new FileInputStream(CONFIG_FILE);
			prop.load(is);
		} catch (IOException e) {
			logger.error("加載配置文件異常:[" + CONFIG_FILE + "], " + e.getMessage(), e);
		} finally {
			if(is != null){
				try {
					is.close();
				} catch (Exception e) {
				}
			}
		}
	}
	
	/**
	 * 得到配置文件中屬性的值
	 * @param key
	 * @return
	 */
	public String getValue(String key) {
		if(reload){
			synchronized (prop) {
				if(reload){
					init();
					reload = false;
				}
			}
		}
		return prop.getProperty(key);
	}
	
	public String getValue(String key, String defaultValue) {
		if(reload){
			synchronized (prop) {
				if(reload){
					init();
					reload = false;
				}
			}
		}
		return prop.getProperty(key, defaultValue);
	}
	
	/**
	 * 更改屬性的值
	 * @param key
	 * @param value
	 * @param isSave, 是否保存到配置文件中
	 */
	public synchronized void setValue(String key, String value, boolean isSave) {
		prop.setProperty(key, value);
		if(isSave){
			FileOutputStream os = null;
			try {
				os = new FileOutputStream(CONFIG_FILE);
				prop.store(os, "");
			} catch (IOException e) {
				logger.error("修改配置文件異常:[" + CONFIG_FILE + "], " + e.getMessage(), e);
			} finally {
				if(os != null){
					try {
						os.close();
					} catch (Exception e) {
					}
				}
			}
		}
	}
	
	/**
	 * 重新加載配置文件中所有屬性
	 */
	public synchronized void reload(){
		this.reload = true;;
	}

以上代碼中,以RUNTIME_HOME的參數方式,動態獲取當前類運行的項目的路徑,在eclipse的主類上右鍵配置運行在彈出的窗口中選擇自變量tab頁的VM自變量中設置

-DRUNTIME_HOME=${workspace_loc:cn.test}參數後,當類運行後就可以取到當前的絕對路徑/cn.test目錄。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章