JDBC使用反射讀取properties文件方法筆記

1,配置文件放到src下  

2,代碼片段

public class CMConstant {
public static String getConfigureParameterFromJDBC(String paramString) {
		String str = CMConstant.getRootPath() + File.separator + "WEB-INF"
				+ File.separator + "classes/config.properties";
		Properties localProperties = new Properties();
		try {
			FileInputStream localFileInputStream = new FileInputStream(str);
			localProperties.load(localFileInputStream);
			localFileInputStream.close();
		} catch (FileNotFoundException localFileNotFoundException) {
			logger.error("讀取屬性文件--->失敗!- 原因:文件路徑錯誤或者文件不存在");
			localFileNotFoundException.printStackTrace();
			return null;
		} catch (IOException localIOException) {
			logger.error("裝載文件--->失敗!");
			localIOException.printStackTrace();
		}
		return localProperties.getProperty(paramString);
	}
	
	public static String getRootPath() {
		String result = null;
		try {
			result = CMConstant.class.getResource("CMConstant.class").toURI()
					.getPath().toString();
		} catch (URISyntaxException e1) {
			e1.printStackTrace();
		}
		int index = result.indexOf("WEB-INF");
		if (index == -1) {
			index = result.indexOf("bin");
		}
		result = result.substring(1, index);
		if (result.endsWith("/"))
			result = result.substring(0, result.length() - 1);// 不包含最後的"/"
		return result;
	}
<span style="white-space:pre">	</span>/**
	 * 查找config/jdbc.properties裏值
	 * @Description: @param key
	 * @Description: @return
	 * @Last Modified: , Date Modified:
	 */
	public static String getJDBCValue(String key) {
		String filePath = getRootPath() + File.separator + "WEB-INF\\classes"
				+ File.separator + "config.properties";
		Properties propertie = new Properties();
		try {
			FileInputStream inputFile = new FileInputStream(filePath);
			propertie.load(inputFile);
			inputFile.close();
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
			return null;
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return propertie.getProperty(key);
	}
}


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