java獲取類加載路徑和項目根路徑的5種方法


        // 第一種:獲取類加載的根路徑   D:\IDEAWorkspace\hs-bluetooth-lock\src\applications\bluetooth-api\target\classes
        File f = new File(this.getClass().getResource("/").getPath());
        System.out.println(f);

        // 獲取當前類的所在工程路徑; 如果不加“/”  獲取當前類的加載目錄  D:\IDEAWorkspace\hs-bluetooth-lock\src\base\target\classes\com\hs\lock\bluetooth\base\utils
        File f2 = new File(this.getClass().getResource("").getPath());
        System.out.println(f2);

        // 第二種:獲取項目路徑    D:\IDEAWorkspace\hs-bluetooth-lock
        File directory = new File("");// 參數為空
        String courseFile = directory.getCanonicalPath();
        System.out.println(courseFile);

        // 第三種:  file:/D:/IDEAWorkspace/hs-bluetooth-lock/src/applications/bluetooth-api/target/classes/
        URL xmlpath = this.getClass().getClassLoader().getResource("");
        System.out.println(xmlpath);

        // 第四種: 獲取當前工程路徑 D:\IDEAWorkspace\hs-bluetooth-lock
        System.out.println(System.getProperty("user.dir"));
  
        // 第五種:  獲取所有的類路徑 包括jar包的路徑
        System.out.println(System.getProperty("java.class.path"));

 


免責聲明!

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



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