Wednesday, March 19, 2008

How To Create a Java Program that Search for a Class file in a JAR File

From rreddy:

1) Create a file called
"SearchJars.java"

2) Put this code and save the file:

 package mypackage7;

import java.util.zip.*;
import java.io.*;
import java.util.*;

public class SearchJars {

static String s3;
static String s4 ="";
static int i1 = 0;
static int i2 = 0;

public static void main(String args[]) {
if (args.length != 2) throw new IllegalArgumentException("Wrong Number of Args !! java SearchJars Direcory_Name filename ");
File f1 = new File(args[0]);
s3 = args[1];
traverse(f1);
System.out.println("\n\n============== Results ============================");
System.out.println("Searced "+ i1 +" Files in "+ args[0] +" And Found "+i2 +" Entries. ");
System.out.println(s4);
}


public static void traverse(File f) {
String s1 = f.getAbsolutePath();

if (s1.toUpperCase().indexOf(".JAR") != -1 || s1.toUpperCase().indexOf(".ZIP") != -1 ) {
System.out.println("Searching "+ s1 +" .....");
i1++;
try {
ZipFile zf = new ZipFile(s1);
for (Enumeration entries = zf.entries(); entries.hasMoreElements();) {
String s2 = ((ZipEntry)entries.nextElement()).getName();
if (s2.indexOf(s3) != -1 ) {
System.out.println("Found "+s2 + " In " +s1);
i2++;
s4 = s4 + "Found "+s2 + " In " +s1 + "\n";
}
}
} catch (IOException e) {}
}

if (f.isDirectory()) {
String[] children = f.list();
for (int i=0; i
traverse(new File(f, children[i]));
}
}
}
}

3) Compile with old/new java
"javac SearchJars.java"

4) Run like this if you want to search a class file name like Create.Users.class in $ORACLE_HOME

./java -cp . SearchJars $ORACLE_HOME CreateUsers.class

5) Above cmd will search for whole $ORACLE_HOME and will return the .JAR file in which this class is stored.

6) Very useful in stack traces and verbose outputs to locate which class file is stored in which jar file.

No comments: