【java】獲取properties配置文件信息工具類


package com.gfan.util;


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

public class GetPropertyUtil {

	// 方法一:通過java.util.ResourceBundle讀取資源屬性文件
	public static String getPropertyByName(String path, String name) {
		String result = "";
		try {
			result = java.util.ResourceBundle.getBundle(path).getString(name);
		} catch (Exception e) {
			System.out.println("getPropertyByName2 error:" + name);
		}
		return result;
	}

	// 方法二:通過類加載目錄getClassLoader()加載屬性文件
	public static String getPropertyByName2(String path, String name) {
		String result = "";
		InputStream in = GetPropertyUtil.class.getClassLoader()
				.getResourceAsStream(path);
		Properties prop = new Properties();
		try {
			prop.load(in);
			result = prop.getProperty(name).trim();
			System.out.println("name:" + result);
		} catch (IOException e) {
			System.out.println("讀取配置文件出錯");
			e.printStackTrace();
		}
		return result;
	}
	
	public static void main(String[] args) {
		//調用不需填寫properties文件後綴
		System.out.println(GetPropertyUtil.getPropertyByName("sms", "PHONE"));
		//帶有路徑的調用
		System.out.println(GetPropertyUtil.getPropertyByName("config/sms", "PHONE"));
	}

}

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