集册 Java实例教程 检索实现

检索实现

欢马劈雪     最近更新时间:2020-01-02 10:19:05

453
从包含指定Class的Jar文件中检索Implementation-Version字符串。

// Licensed under the Apache License, Version 2.0 (the "License");
/**
N o w  J a v a  .   c o m
**/

import java.io.IOException;

import java.io.InputStream;

import java.net.JarURLConnection;

import java.net.URL;

import java.util.jar.Attributes;

import java.util.jar.Manifest;

import java.util.logging.Level;

import java.util.logging.Logger;


public class Main{

    private static final Logger LOGGER = Logger.getLogger(JarUtils.class

            .getName());

    /**

     * Retrieve the Implementation-Version string from the Jar file

     * that contains the specified Class.

     *

     * @param clazz a Class unique to the jar file we are looking for.

     * @return the version string from the Jar file or the empty string

     * ("") if none found.

     */

    public static String getJarVersion(Class<?> clazz) {

        String classPath = "/" + clazz.getName().replace('.', '/')

                + ".class";

        URL classUrl = clazz.getResource(classPath);/*from n o w    j a v a  . c o m*/

        if (classUrl == null) {

            LOGGER.warning("Error accessing Jar Manifest for " + clazz);

            return "";

        }


        // The classUrl may not be a jar: URL, depending on the servlet

        // container, so we can't just open it and assume we'll get a

        // JarURLConnection to get the manifest from. So we construct an

        // URL directly to the manifest we want.

        String classUrlRep = classUrl.toString();

        String path = classUrlRep.replace(classPath,

                "/META-INF/MANIFEST.MF");

        if (path.equals(classUrlRep)) {

            // The replace failed; we don't have an URL to read the manifest from.

            LOGGER.warning("Error accessing Jar Manifest for "

                    + classUrlRep);

            return "";

        }

        try {

            URL url = new URL(path);

            InputStream in = url.openStream();

            Manifest manifest = new Manifest(in);

            Attributes attrs = manifest.getMainAt
展开阅读全文