Using Java to read a .jar manifest file

前端 未结 3 1708
渐次进展
渐次进展 2021-02-06 11:43

so I am trying to see if a .jar is valid or not, by checking some values in the mainfest file. What is the best way to read and parse the file using java? I thought of using thi

3条回答
  •  长发绾君心
    2021-02-06 12:19

    The easiest way is to use JarURLConnection class :

    String className = getClass().getSimpleName() + ".class";
    String classPath = getClass().getResource(className).toString();
    if (!classPath.startsWith("jar")) {
        return DEFAULT_PROPERTY_VALUE;
    }
    
    URL url = new URL(classPath);
    JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
    Manifest manifest = jarConnection.getManifest();
    Attributes attributes = manifest.getMainAttributes();
    return attributes.getValue(PROPERTY_NAME);
    

    Because in some cases ...class.getProtectionDomain().getCodeSource().getLocation(); gives path with vfs:/, so this should be handled additionally.

    Or, with ProtectionDomain:

    File file = new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI());
    if (file.isFile()) {
        JarFile jarFile = new JarFile(file);
        Manifest manifest = jarFile.getManifest();
        Attributes attributes = manifest.getMainAttributes();
        return attributes.getValue(PROPERTY_NAME);
    }
    

提交回复
热议问题