1.获取文件路径
类名.class.getResource("") 表示项目中包的绝对目录(xx/workspace/项目名/包名)
类名.class.getResource("/") 表示项目的绝对目录(xx/workspace/项目名)
类名.class.getResource("/") == 类名.class.getClassLoader().getResource("")(后者path中不能加/)
src对应文件夹下的bin目录
private static Properties prop = new Properties();
private static boolean isLoad = false; // 不重复加载配置文件
public static String getIPConfig(String name) {
if (!isLoad) {
try {
String filePath = Utils.class.getClassLoader().getResource("").getFile();//Utils为当前所在类,即this
filePath = java.net.URLDecoder.decode(filePath, "utf-8");// 转码
prop.load(new FileInputStream(filePath + "/Configs.properties"));//配置文件放在src下
isLoad = true;
} catch (IOException e) {
e.printStackTrace();
}
}
return prop.getProperty(name);
}
注意1.配置文件中不要有""
2.Android(配置文件放在Assets中)
public static String getIPConfig(String name, Context context) {
if (isLoad == false) {
try {
prop.load(context.getAssets().open("IPConfig.properties"));
isLoad = true;
} catch (IOException e) {
e.printStackTrace();
}
}
return prop.getProperty(name);
}