一、根据System getProperties 中user.dir的值查找。
private static Properties pros = new Properties();
private static final String FILENAME = "my.properties";
//加载属性文件
static {
try {
String path = System.getProperty("user.dir") + File.separator + FILENAME;
File file = new File(path);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
pros.load(in);
in.close();
} else {
String filePath = System.getProperty("user.dir");
log.error(path);
log.error("=========>错误:系统未发现配置文件"+FILENAME+"=========");
log.error("配置文件应该放在 "+filePath+"下");
log.error("=========>该文件模板可在jar中获取====================");
}
} catch (Exception e) {
log.error("==================>load configuration error", e);
}
}
特点:user.dir的值取决于执行jar包时所在目录下,若执行jar包不在jar包所在的路径则存在找不到配置文件,未打jar包时,在eclipse中执行此程序则user.dir指的是src同级的路径
二、
private static Properties pros = new Properties();
try {
InputStream in = PropertyUtil.class.getClassLoader().getResourceAsStream("conf/my.properties");
pros.load(in);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
三、
private static Properties pros = new Properties();
try {
URL url = PropertyUtil.class.getProtectionDomain().getCodeSource().getLocation();
String filePath = null;
try {
filePath = URLDecoder.decode(url.getPath(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
if (filePath.endsWith(".jar"))
filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
File file = new File(filePath);
filePath = file.getAbsolutePath();
file = new File(filePath+File.separator+"my.properties");
if (file.exists()) {// 如果为设置的话系统会读取默认配置
FileInputStream in = new FileInputStream(file);
pros.load(in);
in.close();
} else {
System.out.println("=========错误:系统未发现配置文件========");
System.out.println("在 "+filePath+"下未发现配置文件");
System.out.println("=========该文件模板可在jar中获取========");
}
} catch (Exception e) {
e.printStackTrace();
}