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"));
}
}
【java】获取properties配置文件信息工具类
最新推荐文章于 2021-08-04 11:34:11 发布