Wednesday, February 9, 2011

Jar Finder home grown

I republish here my beloved utility to dump the content of all ZIP and JAR files....

I change and use it often, so better have it as a post, rather than in SVN.




package com.pierre.jar;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

public class JarSearcher {
 private static final String BASEDIR = "C:\\ac,e\\repository\\central\\libs";
 //private static final String BASEDIR = "C:\\Temp";
 static FileWriter fstream ;
 static BufferedWriter out;

 public static void main(String[] args) throws Exception {
  fstream = new FileWriter("c:\\out.txt");
  out = new BufferedWriter(fstream);
  JarSearcher jarSearcher = new JarSearcher();
  jarSearcher.findTest(BASEDIR, "");
  out.flush();
  out.close();
 }

 private void findTest(String dirString, String text) throws ZipException, IOException {
  File dir = new File(dirString);
  for (File f : dir.listFiles()) {
   if (f.isDirectory()) {
    findTest(f.getAbsolutePath(), text);
   }
   else {
    String name = f.getName();
    if (name.endsWith(".jar") || name.endsWith(".zip")) {
     System.out.println("SEARCHING " + f.getAbsolutePath());
     out.write("===" + f.getAbsolutePath() + "===\n");
     try {
      ZipFile zipFile = new ZipFile(f);
      Enumeration e =  zipFile.entries();
      while (e.hasMoreElements()) {
       ZipEntry nextElement = e.nextElement();
       InputStream is = zipFile.getInputStream(nextElement);
       if (text.length() == 0 || findInInputStream(is, text)) {
        System.out.println("FOUND ENTRY " + nextElement.getName() + " in file " + f.getAbsolutePath());
        out.write(nextElement.getName() + "\n");
       }
      }
     }
     catch (Exception e) {
      e.printStackTrace();
     }
     out.write("\n\n");
    }
    else {

    }
   }
  }
 }



 private boolean findInInputStream(InputStream is, String text) throws IOException {
  boolean result = false;
  BufferedReader br = new BufferedReader(new InputStreamReader(is));
  String line = null;
  while ( (line = br.readLine()) != null && result == false) {
   if (line.contains(text)) {
    result = true;
   }
  }
  br.close();
  is.close();
  return result;
 }
}




No comments: