代碼對應的工程路徑圖:
<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獲取