我有一个包含任意文件的目录,我想将其包含在我的 jar 中 - 但是,我无法找到一种与导出 ->“可运行 jar”一起使用的方法。我尝试过将目录设为“源路径”的技巧,但当我构建 jar 时它仍然不存在。我意识到我可以手动将它们添加到 jar 中(毕竟它只是一个 zip) - 或者我可以使用 ant 脚本或其他构建系统 - 但我正在寻找适用于开箱即用的 Eclipse“Java 项目”的东西。
这是一个例子。我想尝试加载 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.");
}
}
最佳答案
我将 log4j.properties 添加到我的 src 文件夹中,并将 jar 导出为可运行文件。它起作用了。
关于java - eclipse:在 jar 导出中包含任意文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8856162/