Spring boot:获取项目路径的几种方式

337 阅读1分钟

代码对应的工程路径图:


1、获取当前项目工程下静态资源图片路径,以下两种方法皆可:

/**

  • 方法一

*/
String path = this.getClass().getResource("/static/img/logo.png").getPath();
System.err.println("path:" + path);
// path:C:/Users/Administrator/Desktop/wechat-project/demo/target/classes/static/img/logo.png

/**

  • 方法二

*/
String path2 = this.getClass().getClassLoader().getResource("static/img/logo.png").getPath();
System.err.println("path2:" + path2);
// path2:/C:/Users/Administrator/Desktop/wechat-project/demo/target/classes/static/img/logo.png
2、获取当前类所在的工程路径,以下两种方法皆可:

/**

  • 方法一

*/
String path3 = System.getProperty("user.dir");
System.err.println("path3:" + path3);
// path3:C:UsersAdministratorDesktopwechat-projectdemo

/**

  • 方法二

*/
File file = new File("");
try {
String path4 = file.getCanonicalPath();
System.err.println("path4:" + path4);
} catch (IOException e) {
e.printStackTrace();
}
// path4:C:UsersAdministratorDesktopwechat-projectdemo