Reads the package-names from the given jar-file. - Java Reflection

Java examples for Reflection:Jar

Description

Reads the package-names from the given jar-file.

Demo Code

/*/* w  ww.  j  a  v a2  s . c o  m*/
 * Copyright @ 2006-2010 by The Jxva Framework Foundation
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;
import java.io.File;

import java.io.IOException;

import java.util.Enumeration;
import java.util.HashMap;

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

import java.util.zip.ZipFile;

public class Main {
    /**
     * Reads the package-names from the given jar-file.
     * 
     * @param jarFile the jar file
     * @return an array with all found package-names
     * @throws IOException when the jar-file could not be read
     */
    public static String[] getPackageNames(File jarFile) throws IOException {
        HashMap<String, String> packageNames = new HashMap<String, String>();
        JarFile input = new JarFile(jarFile, false, ZipFile.OPEN_READ);
        Enumeration<JarEntry> enumeration = input.entries();
        for (; enumeration.hasMoreElements();) {
            JarEntry entry = enumeration.nextElement();
            String name = entry.getName();
            if (name.endsWith(".class")) {
                int endPos = name.lastIndexOf('/');
                boolean isWindows = false;
                if (endPos == -1) {
                    endPos = name.lastIndexOf('\\');
                    isWindows = true;
                }
                name = name.substring(0, endPos);
                name = name.replace('/', '.');
                if (isWindows) {
                    name = name.replace('\\', '.');
                }
                packageNames.put(name, name);
            }
        }
        return packageNames.values().toArray(
                new String[packageNames.size()]);
    }
}

Related Tutorials