2012-01-13 175 views
1

我有一個我想包含在我的jar文件中的任意文件的目錄 - 但是,我找不到一種方法來處理export - >「Runnable jar」。我已經嘗試過將目錄設置爲'源代碼路徑'的技巧,但在構建jar時它仍然不存在。我意識到我可以手動將它們添加到jar中(畢竟它只是一個zip) - 或者我可以使用一個ant腳本或其他構建系統 - 但我正在尋找一些適用於某種即時可用的應用程序,盒子Eclipse「Java項目」。eclipse:在jar包中包含abitrary文件

下面是一個例子。我想嘗試加載log4j.properties,如果它存在。如果不是,我想從我的jar文件中包含的「默認」中寫出它。最後,如果失敗,它會加載默認值。

請注意,我不知道如果下面的代碼工作,它可能需要調整。我並不是在尋求幫助,我只是給我想要做的事情提供背景。

 // initialize logging libraries 
    File log4jFile = new File("log4j.properties"); 
    if (log4jFile.exists() & log4jFile.canRead()) { 
     PropertyConfigurator.configure(log4jFile.getAbsolutePath()); 
    } 
    else { 
     try { 
      InputStream log4jJarstream = Main.class.getResourceAsStream(sepd + "resources" + sep + "log4j.properties"); 
      OutputStream outStream = new FileOutputStream(new File("log4j.properties")); 
      int read = 0; 
      byte[] bytes = new byte[1024]; 

      while ((read = log4jJarstream.read(bytes)) != -1) { 
       outStream.write(bytes, 0, read); 
      } 
      log4jJarstream.close(); 
      outStream.flush(); 
      outStream.close(); 
     } 
     catch (Exception e) { 
      BasicConfigurator.configure(); 
      log.warn("Error writing log4j.properties, falling back to defaults."); 
     } 
    } 

回答

0

將代碼加載爲資源時發生錯誤......它似乎是Eclipse「看到」的,並且因此拒絕打包該文件。我將文件放在類文件的旁邊,改變了我搜索文件的方式,並將它與.class文件打包在一起,並且可以在執行過程中進行讀取。新代碼片段:

// initialize logging libraries 
    File log4jFile = new File("log4j.properties"); 
    if (log4jFile.exists() & log4jFile.canRead()) { 
     PropertyConfigurator.configure("log4j.properties"); 
    } 
    else { 
     try { 
      InputStream log4jJarstream = Main.class.getResourceAsStream("log4j.properties"); 
      OutputStream outStream = new FileOutputStream(new File("log4j.properties")); 
      int read = 0; 
      byte[] bytes = new byte[1024]; 

      while ((read = log4jJarstream.read(bytes)) != -1) { 
       outStream.write(bytes, 0, read); 
      } 
      log4jJarstream.close(); 
      outStream.flush(); 
      outStream.close(); 

      PropertyConfigurator.configure("log4j.properties"); 
     } 
     catch (Exception e) { 
      BasicConfigurator.configure(); 
      log.warn("Error writing log4j.properties, falling back to defaults."); 
      log.warn(e); 
      log.warn("STACK TRACE:"); 
      int i = 0; 
      StackTraceElement[] trace = e.getStackTrace(); 
      while (i < trace.length) { 
       log.warn(trace[i]); 
       i++; 
      } 
     } 
    } 
0

只是一味出口 - > JAR文件而不是出口運行的JAR文件:它可以讓你選擇多個資源在生成的壓縮文件包含。

您也可以指定Main-Class屬性,就像後面的選項一樣。

順便說一句,如果您使用某種構建工具(如Ant <jar> targetMaven Jar plugin),則更方便。如果您使用Eclipse來生成JAR文件,還可以選擇保存一個Ant構建文件,以便稍後爲您執行此任務。

+0

我已經找到解決方案,但還不能接受它。看到我自己的回答我的問題。 – draeath 2012-01-14 20:13:11

1

我將log4j.properties添加到了我的src文件夾,並將該jar導出爲可運行的。有效。