Retrieves a Manifest object or creates an empty Manifest object if the Manifest is not found in the given Jar file - Java Reflection

Java examples for Reflection:Jar

Description

Retrieves a Manifest object or creates an empty Manifest object if the Manifest is not found in the given Jar file

Demo Code


//package com.java2s;

import java.io.File;

import java.io.IOException;

import java.util.Enumeration;

import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import java.util.jar.Manifest;

public class Main {
    public static final String META_INF = "META-INF";

    /**/*ww  w . j a  v  a 2 s.c  o  m*/
     * Retrieves a Manifest object or creates an empty Manifest object 
     * if the Manifest is not found in the given Jar file
     * @param jarFile
     * @return
     * @throws IOException
     */
    public static Manifest getManifest(File jarFile) throws IOException {
        JarFile jar = new JarFile(jarFile);
        String manifestPath = META_INF + "/MANIFEST.MF";
        JarEntry jarEntry = jar.getJarEntry(manifestPath);
        if (jarEntry != null) {
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                jarEntry = (JarEntry) entries.nextElement();
                if (manifestPath.equalsIgnoreCase(jarEntry.getName())) {
                    break;
                } else {
                    jarEntry = null;
                }
            }
        }
        Manifest manifest = new Manifest();
        if (jarEntry != null) {
            manifest.read(jar.getInputStream(jarEntry));
        }
        jar.close();
        return manifest;
    }
}

Related Tutorials