天天看點

.java編寫庫關鍵字搜尋----針對js等庫

今天開始分析 DWZ架構的源代碼,發現單單從txt來看實在是不好分析,各種函數都不是到是哪裡定義的...

因為javascript的函數定義方法不像java C++等語言有固定的文法,可以模糊比對 ..

對于js這樣的 函數隻能通過關鍵字搜尋代碼如下 直接 javac  java就可以運作 

   import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.Collection;

import java.util.Scanner;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

/**

 * js檔案關鍵字批量搜尋.. 

 * 初衷是搜尋js..可以針對于所有類型可讀檔案

 * 可以從一個path下的js檔案中定位指定關鍵字.....

 * 在分析大規模的js庫的時候可以友善定位關鍵字所在位置..

 * @author 嶽東衛

 */

public class JFunctionFinder {  

 public JFunctionFinder() {

  }

 /**

  * 存放搜尋結果集合

  */

 private Collection<String> col=new ArrayList<String>() ;

   /**傳回庫目錄下所有js檔案

    * @param path  js檔案所在的路徑

    * @return 一個目錄下的所有檔案内容

    * @throws Exception

    */

   private   static  File[] getFile(String  path) throws Exception{

    File f =null;

    try{

    f=new  File(path) ;

    }catch (Exception e) {

  throw new Exception("路徑不存在",e) ;

 } 

 return f.listFiles() ;  //js檔案集合

   }

   /**

    * 遞歸周遊

    * @param  files  getFile結果   一個File數組

    * @param  functionName   要搜尋的關鍵字名字..嚴格區分大小寫

    * @return 傳回一個function所在位置的集合... 

    * @throws IOException

   private void getFunctionLocation(File[]files,String functionName) throws IOException {

    for(File f:files){ 

   //如果是檔案夾 那麼遞歸

     if(f.isDirectory()){  

          try {

       File []tem=getFile(f.getPath()) ;

       this.getFunctionLocation(tem, functionName) ;

          } catch (Exception e) {

        e.printStackTrace();

         }

     }

     //如果是普通js檔案

     else{

      InputStream is=new FileInputStream(f) ;

      byte []bt=new byte[is.available()]; 

      is.read(bt) ;

      String contents=new String(bt) ;//預設unicode編碼..   

      Pattern p=Pattern.compile(functionName,Pattern.MULTILINE) ;  

      Matcher m=p.matcher(contents) ;

      if(m.find()){

       col.add("["+new String(f.getName())+"]\n") ;

      }

       }   

    }

    * 傳回搜尋結果

    * @return

   public Collection<String> getResult(){

    return this.col ;

    * 隻需要調用這個函數開始搜尋就行.,

    * @param path   搜尋路徑如  D:\lib

    * @param functionName 函數名字 嚴格區分大小

    * @return 傳回搜尋結果的集合 ...

   public Collection<String>  beginSearch(String  path,String functionName){  

    this.col.add("存在"+functionName+"的庫檔案是:") ;

    try {

  File []f=getFile(path) ; 

  this.getFunctionLocation(f, functionName) ; 

 } catch (Exception e) {

  e.printStackTrace();

 }

 return col; 

   public static void main(String[] args) throws IOException, Exception {

   JFunctionFinder f=new JFunctionFinder() ;  //建立一個對象 

   System.out.println("請輸入庫檔案的路徑:");

   String path=(new Scanner(System.in)).next() ;  //輸入路徑 如: d:\lib

   System.out.println("輸入關鍵字:");

   String key=(new Scanner(System.in)).next() ;  //輸入路徑 如: d:\lib

   Collection<String> c=f.beginSearch(path, key) ;//傳回存在關鍵字的集合

   for(String s:c){

    System.out.print(s);

   }