java 项目得到jar和classes路径

java 项目得到jar和classes路径 

 

    public static String getJarPath(Class clazz) {
        String path = clazz.getProtectionDomain().getCodeSource().getLocation().getFile();
        try {
            path = java.net.URLDecoder.decode(path, "UTF-8");
            java.io.File jarFile = new java.io.File(path);
            return java.net.URLDecoder.decode(jarFile.getParentFile().getAbsolutePath(), "UTF-8");
        } catch (java.io.UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String getClassesPath(Class clazz) {
        String path = clazz.getClassLoader().getResource("").getPath();
        try {
            return java.net.URLDecoder.decode(path, "UTF-8");
        } catch (java.io.UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

比如在AppTest.java中,

        String path = getClassesPath(AppTest.class);
        print(path);

显示为:

        /C:/workspace1/yourproject/target/test-classes/


你可能感兴趣的:(java 项目得到jar和classes路径)