/** * 第一種:獲取類加載的根路徑 D:\Work\IdeaProjects\HelloVelocity\target\classes */ File f = new File(ControllerUtils.class.getClass().getResource("/").getPath()); System.out.println("第一種:獲取類加載的根路徑"); System.out.println(f); // 獲取當前類的所在工程路徑; 若是不加「/」獲取當前類的加載目錄 D:\IdeaProjects\cdby_wan\WebRoot\WEB-INF\classes\test\com File f2 = new File(ControllerUtils.class.getClass().getResource("").getPath()); System.out.println(f2); /** * 第二種:獲取項目路徑 D:\Work\IdeaProjects\HelloVelocity */ File directory = new File("");// 參數爲空 String courseFile = directory.getCanonicalPath(); // Tomcat環境中運行,會獲取Tomcat安裝目錄的bin目錄,不推薦使用 System.out.println("第二種:獲取項目路徑"); System.out.println(courseFile); /** * 第三種: /D:/Work/IdeaProjects/HelloVelocity/target/classes/ */ String path = ControllerUtils.class.getClassLoader().getResource("").getPath(); System.out.println("第三種:"); System.out.println(path); /** * 第四種: D:\Work\IdeaProjects\HelloVelocity * 結果: C:\Documents and Settings\Administrator\workspace\projectName * 獲取當前工程路徑 */ System.out.println("第四種:"); System.out.println(System.getProperty("user.dir")); /** * 第五種: 獲取全部的類路徑 包括jar包的路徑 */ System.out.println(System.getProperty("java.class.path"));