2014-02-17 96 views
0

我必須讀取腳本包中可用的所有java文件名來執行特定的方法。 下面的代碼使用eclipse可以正常工作。 我想運行使用Runnable Jar的測試 - 作爲strTestScriptsPath =「src/com/xyz/test/scripts」包含src,它變得失敗
(否則我必須提供src文件夾到JAR文件成功運行的話)Runnable Jar文件 - src文件路徑問題

在這種情況下如何使用this.getClass()的getResourceAsStream()

注:我試圖給目錄不是文件的路徑。我已經從上面的代碼只:(

enter image description here

 public static boolean executeKeyword(String keyword){ 
      String strTestScriptsPath = "src/com/xyz/test/scripts";  

      File folder = new File(strTestScriptsPath); 

      File[] listOfFiles = folder.listFiles(); 

      boolean booFindMethod = false; 
      findKeyword: 
      for(File file: listOfFiles){ 


       strJavaClassFileName = FilenameUtils.removeExtension(file.getName());       
       strJavaClassFileName = "com.xyz.test.scripts." + strJavaClassFileName;    

       System.out.println(strJavaClassFileName); 

       // Reflection API code to call the required method from the class 
       .. 
       .. 

      } 
     } 
+0

jar文件應位於../src – Bhoot

回答

0

得到了t時的解決方案他網。 以下是可以從JAR文件中獲取包的類的列表的方法。

public static List<String> getJarFileListing(String jarLocation, String filter) { 
     List<String> files = new ArrayList<String>(); 
     if (jarLocation == null) { 
      return files; // Empty. 
     } 

     // Lets stream the jar file 
     JarInputStream jarInputStream = null; 
     try { 
      jarInputStream = new JarInputStream(new FileInputStream(jarLocation)); 
      JarEntry jarEntry; 

      // Iterate the jar entries within that jar. Then make sure it follows the 
      // filter given from the user. 
      do { 
       jarEntry = jarInputStream.getNextJarEntry(); 
       if (jarEntry != null) { 
        String fileName = jarEntry.getName(); 

        // The filter could be null or has a matching regular expression. 
        if (filter == null || fileName.matches(filter)) { 
         files.add(fileName); 
        } 
       } 
      } 
      while (jarEntry != null); 
      jarInputStream.close(); 
     } 
     catch (IOException ioe) { 
      throw new RuntimeException("Unable to get Jar input stream from '" + jarLocation + "'", ioe); 
     } 
     return files; 
    } 

,並調用上面的函數..

public static void main(String args[]) throws IOException{ 
    List<String> listOfFiles = getJarFileListing("C:\Users\abc\xyz.jar","^com/xyz/test/scripts(.*)"); 
    /* Reflection API code */ 
    } 
    } 
0

哈努曼fectch文件名,如果你想創建一個可運行的罐子,你需要配置清單文件,通過提供完整的類名。隨着這一類應該有:

public static void main(String[] args) { 

詳細信息,請訪問:http://introcs.cs.princeton.edu/java/85application/jar/jar.html

+0

@尼基爾,感謝您的答覆。我已經提供了具有main方法的Main類並且JAR正在運行。這裏的問題是代碼中的路徑。請再次閱讀該問題 – Hanumanth

+0

1.您是否具有對文件夾的讀取權限。 2. com.xyz.test.scripts。是準確的,如果您可以發佈項目結構的圖像將會很有幫助。 3.您已將測試包作爲JAR的一部分?請用命令檢查它:jar tf jar-file-name –

+0

正如我所說的,這是行strTestScriptsPath =「src/com/xyz/test/scripts」的問題。 由於JAR文件包含com/xyz/test/scripts作爲文件結構,因此無法找到src。 – Hanumanth