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()就可得到。

posted @ 2013-06-29 19:16  华电岳黎明  阅读(8067)  评论(0编辑  收藏  举报