java中获得jar包执行路径的方法


  当我们由于某种需要需要的得到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()就可得到。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM