reading MANIFEST.MF file from jar file using JAVA

前端 未结 8 1350
情深已故
情深已故 2020-12-02 20:34

Is there any way i can read the contents of a jar file. like i want to read the manifest file in order to find the creator of the jar file and version. Is there any way to a

8条回答
  •  忘掉有多难
    2020-12-02 20:52

    Keep it simple. A JAR is also a ZIP so any ZIP code can be used to read the MAINFEST.MF:

    public static String readManifest(String sourceJARFile) throws IOException
    {
        ZipFile zipFile = new ZipFile(sourceJARFile);
        Enumeration entries = zipFile.entries();
    
        while (entries.hasMoreElements())
        {
            ZipEntry zipEntry = (ZipEntry) entries.nextElement();
            if (zipEntry.getName().equals("META-INF/MANIFEST.MF"))
            {
                return toString(zipFile.getInputStream(zipEntry));
            }
        }
    
        throw new IllegalStateException("Manifest not found");
    }
    
    private static String toString(InputStream inputStream) throws IOException
    {
        StringBuilder stringBuilder = new StringBuilder();
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)))
        {
            String line;
            while ((line = bufferedReader.readLine()) != null)
            {
                stringBuilder.append(line);
                stringBuilder.append(System.lineSeparator());
            }
        }
    
        return stringBuilder.toString().trim() + System.lineSeparator();
    }
    

    Despite the flexibility, for just reading data this answer is the best.

提交回复
热议问题