//还有个方法,可能更好,可获取:
最好的方式
1.以jar包运行(可以,返回路径 F:/self/Source/baseframe/baseframe.jar!/BOOT-INF/classes!/,
需找到根路径 new File(“F:/self/Source/baseframe/baseframe.jar!/BOOT-INF/classes!/“).getParentFile().getParentFile().getParentFile().getPath())
2.idea调试 (可以 到 classes)
3.以war包 ,tomcat运行(可以到 classes)
ApplicationConfig.class.getProtectionDomain().getCodeSource().getLocation().getPath()
获取.properties,以下3种方式运行均可以
1.以jar包运行(可以)
2.idea调试 (可以)
3.以war包 ,tomcat运行(可以)
private static final String propertiesFileName = “config/applicationConfig.properties”;// 路径
private static Properties p = new Properties();
private static String fixPath;
static Logger logger = LoggerFactory.getLogger(ApplicationConfig.class);
// 加载配置文件<br /> /*static {<br /> try {<br /> fixPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();<br /> fixPath = URLDecoder.decode(fixPath, "utf-8");<br /> if (fixPath.startsWith("/")) {<br /> fixPath = fixPath.substring(1);// 返回‘/’以后的字符串<br /> }<br /> String propertiesPath = fixPath + propertiesFileName;<br /> InputStream inputStream = new FileInputStream(propertiesPath);<br /> //使用API内配置文件方式<br /> //InputStream inputStream =TestProperties.class.getResourceAsStream("/config/config.properties");<br /> BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream, "gbk"));<br /> p.load(bf);<br /> inputStream.close();<br /> } catch (Throwable e) {<br /> e.printStackTrace();<br /> }<br /> }*/<br /> static {<br /> try {<br /> Resource resource = new ClassPathResource(propertiesFileName);<br /> InputStream is = resource.getInputStream();<br /> InputStreamReader isr = new InputStreamReader(is, "gbk");<br /> BufferedReader br = new BufferedReader(isr);<br /> p.load(br);<br /> isr.close();
} catch (Throwable e) {<br /> e.printStackTrace();<br /> }<br /> }
//获取类资源路径 classes,资源文件在这里
1.以jar包运行(不可以,找不到路径)
2.idea调试 (可以 到 classes)
3.以war包 ,tomcat运行(可以到 classes)public static String getResourcesPath**() throws IOException {
Resource resource = new ClassPathResource(“”);
String path = ((ClassPathResource) resource).getFile().getPath();
return path + (**StringUtils._endsWith(path, “/“) ? “” : “/“);
}
获取jar包运行路径
1.以jar包运行(可以,根目录)
2.idea调试 (可以 到target 根目录)
3.以war包 ,tomcat运行(到WEB-INFO,未到classes级 )
public static String getJarPath(){
ApplicationHome applicationHome = new ApplicationHome(ApplicationConfig.class);
File source = applicationHome.getSource();
//路径处理,获取到的jar包所在位置
String filePath = source.getParentFile().getAbsolutePath();
return filePath;
}
获取类路径资源路径下的非Properties 文件,以上均无法做到,因为资源文件在jar包内不能直接读取
https://blog.csdn.net/zhongguowangzhan/article/details/107727401
https://www.jianshu.com/p/b01baf809d9d
建议拿到单独目录,配置路径