java搜索jar包中的指定字符串
1 package com.niu.jit; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.InputStreamReader; 6 import java.util.ArrayList; 7 import java.util.Enumeration; 8 import java.util.List; 9 import java.util.zip.ZipEntry; 10 import java.util.zip.ZipFile; 11 12 /** 13 * 寻找指定路径下jar包中含特定字符串的文件 15 */ 16 public class FindStrInJar { 17 18 public String condition; //查询的条件 19 20 public ArrayList<String> jarFiles = new ArrayList<String>(); 21 22 public FindStrInJar() { 23 } 24 25 public FindStrInJar(String condition) { 26 this.condition = condition; 27 } 28 29 public FindStrInJar(String condition, String exclude) { 30 this.condition = condition; 31 } 32 33 public void setCondition(String condition) { 34 this.condition = condition; 35 } 36 37 public List<String> find(String dir, boolean recurse) { 38 searchDir(dir, recurse); 39 return this.jarFiles; 40 } 41 42 public List<String> getFilenames() { 43 return this.jarFiles; 44 } 45 46 protected String getClassName(ZipEntry entry) { 47 StringBuffer className = new StringBuffer(entry.getName().replace("/", ".")); 48 return className.toString(); 49 } 50 51 @SuppressWarnings("unchecked") 52 protected void searchDir(String dir, boolean recurse) { 53 try { 54 File d = new File(dir); 55 if (!d.isDirectory()) { 56 return; 57 } 58 File[] files = d.listFiles(); 59 for (int i = 0; i < files.length; i++) { 60 if (recurse && files[i].isDirectory()) { 61 searchDir(files[i].getAbsolutePath(), true); 62 } else { 63 String filename = files[i].getAbsolutePath(); 64 if (filename.endsWith(".jar")||filename.endsWith(".zip")) { 65 ZipFile zip = new ZipFile(filename); 66 Enumeration entries = zip.entries(); 67 while (entries.hasMoreElements()) { 68 ZipEntry entry = (ZipEntry) entries.nextElement(); 69 String thisClassName = getClassName(entry); 70 71 //不搜索扩展名为.class的文件 72 // if(thisClassName.lastIndexOf(".class")==-1){ 73 BufferedReader r = new BufferedReader(new InputStreamReader(zip.getInputStream(entry))); 74 while(r.read()!=-1){ 75 String tempStr = r.readLine(); 76 if(null!=tempStr && tempStr.indexOf(condition)>-1){ 77 this.jarFiles.add(filename + " ---> " + thisClassName); 78 break; 79 } 80 } 81 // } 82 83 } 84 } 85 } 86 } 87 } catch (Exception e) { 88 e.printStackTrace(); 89 } 90 } 91 92 public static void main(String args[]) { 93 FindStrInJar findInJar = new FindStrInJar("神秘字符串"); //要寻找的字符串 94 List<String> jarFiles = findInJar.find("D:\\test\\lib", true); 95 if (jarFiles.size() == 0) { 96 System.out.println("Not Found"); 97 } else { 98 for (int i = 0; i < jarFiles.size(); i++) { 99 System.out.println(jarFiles.get(i)); 100 } 101 } 102 } 103 104 }