Spring boot:獲取項目路徑的幾種方式


代碼對應的工程路徑圖:

<ignore_js_op> 
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:\Users\Administrator\Desktop\wechat-project\demo

/**
* 方法二
*/
File file = new File("");
try {
   String path4 = file.getCanonicalPath();
   System.err.println("path4:" + path4);
} catch (IOException e) {
   e.printStackTrace();
}
// path4:C:\Users\Administrator\Desktop\wechat-project\demo

更多java學習資料可關注:itheimaGZ獲取


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM