美文网首页
JarPathTool 对jar的操作

JarPathTool 对jar的操作

作者: 我是晓梦啊 | 来源:发表于2021-10-26 15:29 被阅读0次
import java.io.File;

public class JarPathTool {

    public static String getJarDir3() {
        return System.getProperty("user.dir");
    }

    public static String getJarDir2() {
        String path = System.getProperty("java.class.path");
        int firstIndex = path.lastIndexOf(System.getProperty("path.separator")) + 1;
        int lastIndex = path.lastIndexOf(File.separator) + 1;
        path = path.substring(firstIndex, lastIndex);
        return path;
    }

    //获取jar绝对路径 
    public static String getJarPath(){ 
        File file = getFile();
        if(file==null)return null; 
         return file.getAbsolutePath(); 
    } 
    //获取jar目录 
    public static String getJarDir() { 
        File file = getFile(); 
        if(file==null)return null; 
         return getFile().getParent(); 
    } 
    //获取jar包名 
    public static String getJarName() { 
        File file = getFile(); 
        if(file==null)return null; 
        return getFile().getName(); 
    } 
   
    private static File getFile() { 
        //关键是这行... 
        String path = JarPathTool.class.getProtectionDomain().getCodeSource()
                .getLocation().getFile(); 
        try{ 
            path = java.net.URLDecoder.decode(path, "UTF-8");//转换处理中文及空格 
        }catch (java.io.UnsupportedEncodingException e){ 
            return null; 
        } 
        return new File(path); 
    }

    public static void main(String[] args) {
        System.out.println(getJarPath());
        System.out.println(getJarDir());
    }
       
}

相关文章

网友评论

      本文标题:JarPathTool 对jar的操作

      本文链接:https://www.haomeiwen.com/subject/hjfadltx.html