2014-03-06 51 views
0

我有一個JAR文件,我想搜索其中的類文件的存在。如何在JAR中搜索文件?

import java.util.jar.*; 

public class Check 
{ 
    public static void main(String args[]) throws Exception 
    { 
     String path="C:\\workspace\\Project\\sun\\tools\\jam-dt.jar"; 
     path=path.replace("\\","/"); 
     JarFile jar=new JarFile(path); 

     JarEntryentry=jar.getJarEntry("com/sun/xml/ws/binding/Bind.class"); 
    if(entry!=null) 
    { 
     System.out.println(" Entry present"); 

    } 
    else 
    { 
     System.out.println("No Entry"); 
    } 
} 

}

然而,有存在的JAR文件中的許多目錄。我不能在getJarEntry函數中手動輸入每一個函數並檢查。如何檢查一個類是否存在。如何在JAR中搜索文件?

+0

澄清 - 您知道要搜索的文件的名稱(Bind.class),但不知道它將在哪個目錄中? –

+1

爲什麼你不能遍歷jar中的每個條目?如果班級出現在兩個不同的包中,你希望發生什麼? –

+0

@mattb是的..那裏有emany目錄搜索.. – user2133404

回答

2
String path="C:/Users/hussain.wahid/Desktop/hussain back up/Hussain/Eclipse WorkSpace/SO/poi.jar"; 
     path=path.replace("\\","/"); 
     JarFile jar=new JarFile(path); 
     ArrayList<String> fileNameList = new ArrayList<String>(); 

     Enumeration<JarEntry> myEntry = jar.entries(); 
     while(myEntry.hasMoreElements()) 
     { 
      //System.out.println(myEntry.nextElement().toString()); 
      fileNameList.add(myEntry.nextElement().toString()); 
     } 
     System.out.println(fileNameList.contains("com/sun/xml/ws/binding/Bind.class")); 
     //org/apache/poi/hssf/record/aggregates/ 

我試圖更簡單地理解

順便說一句引入數組列表是完全未必要

Enumeration<JarEntry> myEntry = jar.entries(); 
      while(myEntry.hasMoreElements()) 
      { 
System.out.println(myEntry.nextElement().toString().equals("org/apache/poi/hssf/record/aggregates/")); 
      } 
+0

謝謝你..它爲我工作 – user2133404

+0

@ user2133404:看到編輯 –

0

使用JarFile.entries()並遍歷它們。

0

您可以使用下面的Linux命令在一個jar文件搜索類:

的jar -tvf myjar.jar | grep的com.sun.xml.ws.binding.Bind.class