2012-01-13 173 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导出为可运行的。有效。