Tuesday, February 15, 2011

ClassFinder in java

How to find out a class file in a JAR/WAR/ZIP files using java

ClassFinder program to findout "simulator.class" in a dwr.jar file
 
package com.vels.sms.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
 /**
 * @author velmurugan pousel
 * @project SMS
 * created on Feb 14, 2011
 */
public class ClassNameFinder {
 

 public static List<String> findClass(String srcJarPath, String srcJar) throws IOException{
  List<String> nameList = new ArrayList<String>();

  ZipFile zip = new ZipFile(srcJarPath);  
  // Process the zip file. Close it when the block is exited.
  try {
      
    String searchFileC = srcJar+".class";
    String searchFileJ = srcJar+".java";
  
   // Loop through the zip entries and print the name of each one.

   for (Enumeration list = zip.entries(); list.hasMoreElements();) {
         ZipEntry entry = (ZipEntry) list.nextElement();
        String srcFile = entry.getName();

    // filters only .class and java files..avoids unnecesaary checking

       if (srcFile.endsWith(".class") || srcFile.endsWith(".java")) {
                   int c = srcFile.lastIndexOf("/");
                  String fName = srcFile.substring(c + 1);
                 if (searchFileC.equalsIgnoreCase(fName) || searchFileJ.equalsIgnoreCase(fName)) {     
                     nameList.add(srcFile);
                  }
        }
   }

//   if(!fileFound){
//    System.out.println(" File" + srcJar +"  not found on the "+ srcJarPath);
//   }
        
  } catch (Throwable e) {
            e.printStackTrace();
  } finally {
            zip.close();
  }
            return nameList;
 }

 public static void main(String[] args) {
  try {
          String srcPath = "D:\\bak\\dwr.war";
          String searchFile = "simulator";
  
         List<String> classList = findClass(srcPath, searchFile);
  
        if (classList.size()>0){
            System.out.println(" Class Find..."+ classList);
       } else {
            System.out.println(" File" + srcPath +"  not found on the "+ searchFile);
       }
     
  } catch (Throwable e){
       e.printStackTrace();
  }
  
 }

}

.....
....

No comments:

Post a Comment