類名.class.getClassLoader().getResource("/").getPath()獲取路徑信息


類名.class.getClassLoader().getResource("/").getPath()獲取的項目路徑是項目打包后在target中的路徑.
例1:

String classPath = Util.class.getClassLoader().getResource("/").getPath();
 獲取到的類路徑是

/D:/workspaceGit/project-model/project-model-web/target/model-web/WEB-INF/classes/
 例1中Util是公共的包中的類,引用或繼承引用在project-model項目的模塊project-model-web中,所以獲取到的路徑是上述路徑classes包中。

例子2:

String classPath = Util.class.getClassLoader().getResource("../../").getPath();
獲取到的路徑是

/D:/workspaceGit/project-model/project-model-web/target/model-web/
其中"../../"指的是上上級目錄。

例子3:

this.getClass().getResource("").getPath()
獲取到的路徑是

 

/D:/workspaceGit/project-model/project-model-web/target/model-web/WEB-INF/classes/com/model/modelA/controller/
一般做公用的工具方法,要適應引用包的所有項目,要用例1與例2.

資料項目中獲取資源文件路徑 方法有

1、xxx.class.getClassLoader().getResource(“”).getPath(); 
獲取src資源文件編譯后的路徑(即classes路徑)


2、xxx.class.getClassLoader().getResource(“文件”).getPath(); 
獲取classes路徑下“文件”的路徑


3、xxx.class.getResource(“”).getPath(); 缺少類加載器,獲取xxx類經編譯后的xxx.class路徑


4、this.getClass().getClassLoader().getResource(“”).getPath();
————————————————
版權聲明:本文為CSDN博主「阿爾法小師妹」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_41926301/article/details/83818927


免責聲明!

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



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