Scanning Jar File Example

0

In this article we will see how to scan a jar file.
We will export class A, class B and test.properties to a jar file called example.jar.

Create Jar File

Create Jar File

We will use JarInputStream class to read the contents of the JAR file. If you want to read the contents zip file, use ZipInputStream, here is an example.

JarInputStream extends ZipInputStream, in order to read the next jar entry, call getNextJarEntry() on JarInputStream.

JavaScanningJarExample:

package com.javarticles.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

public class JavaScanningJarExample {
    public static void main(String[] args) throws IOException,
            ClassNotFoundException {
        File f = new File("example.jar");
        FileInputStream fis = new FileInputStream(f);
        JarInputStream jis = new JarInputStream(fis);
        try {
            JarEntry next = jis.getNextJarEntry();
            while (next != null) {
                final String name = next.getName();
                System.out.println("Jar file: " + name);
                next = jis.getNextJarEntry();
            }
        } finally {
            jis.close();
        }
    }
}

Output:

Jar file: com/javarticles/jar/resources/test.properties
Jar file: com/javarticles/jar/A.class
Jar file: com/javarticles/jar/B.class

Download the source code

This was an example about scanning a jar file using JarInputStream.

You can download the source code here: javaScanningJarExample.zip

About Author

Ram’s expertise lies in test driven development and re-factoring. He is passionate about open source technologies and loves blogging on various java and open-source technologies like spring.
You can reach him at [email protected]

Comments are closed.