今天在开发中做一个java项目,要求读取配置文件中的信息,开始一直写成绝对路径,当项目打jar包以后就找不到配置文件了,后面在网上当了一个方法,问题最后解决了,拿出来跟大家分享一下。
/**
* 获得项目所在路径
* @return String
*/
public static String getPath() {
URL url = UtilTools.class.getResource("");
File file = new File(url.getFile());
String path = file.getParent();
while (-1 != path.lastIndexOf("bin") || -1 != path.lastIndexOf(".jar")) {
file = new File(path);
path = file.getParent();
}
if (path.startsWith("file")) {
path = path.replaceAll("file:", "");
}
path = path + File.separator+"JmailConfig.xml"
return path;
}