當我們由於某種需要需要的得到jar的路徑是可以用下面的方式來獲得:
basePath = new Solution().getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); basePath = URLDecoder.decode(basePath,"utf-8"); System.out.println("basePaht:"+basePath); if(basePath.endsWith(".jar")){ basePath = basePath.substring(0,basePath.lastIndexOf("/")+1); }
File f = new File(basePath);
basePath = f.getAbsolutePath(); //得到windows下的正確路徑
其中Solution為main函數所在類的類名稱,如果路徑中有中文的話需要用URLDecoder.decode(basePath,"utf-8")utf-8進行轉碼,其中得到的basePath即為jar包的父路徑,到現在為止,得到的路徑還不是Windows下的格式,應用f.getAbsolutePath()就可得到。