gpt4 book ai didi

java - 如何制作包含 DLL 文件的 JAR 文件?

转载 作者:IT老高 更新时间:2023-10-28 13:52:37 28 4
gpt4 key购买 nike

我购买了一个第三方 Java 库,其中包括一个 JAR 文件和两个 DLL 文件。我编写了自己的 Java 程序来调用第三方 JAR 文件。现在我的问题是如何将我的所有代码打包到一个 JAR 文件中,其中包含我的所有代码以及第三方 JAR 和 DLL?

我知道 SWT 就是这种情况。 swt.jar 包含 dll 文件,但我不知道如何执行此操作以及如何使其正常工作。

最佳答案

只需将它打包到 jar 中的任何位置。不过,您必须记住一件事 - 在您可以使用 DLL 之前,您需要从 JAR 中实际提取它们并将它们转储到硬盘上的某个地方,否则您将无法加载这些

所以基本上 - 我为客户做了 JNI 项目,我将在 war 中使用这样的 jar 包。但是 - 在运行任何 native 方法之前,我会将 DLL 作为资源并将其写入磁盘的临时目录中。然后我会运行常规初始化代码,其中我的 DLL 设置到我刚刚将 DLL 写入的位置

哦,以防万一:将 dll 或任何其他文件打包到 jar 中并没有什么特别之处。就像把东西打包成 zip 一样

这是我刚刚挖掘出来的一些代码

public class Foo {
private static final String LIB_BIN = "/lib-bin/";
private final static Log logger = LogFactory.getLog(ACWrapper.class);
private final static String ACWRAPPER = "acwrapper";
private final static String AAMAPI = "aamapi51";
private final static String LIBEAU = "libeay32";

static {
logger.info("Loading DLL");
try {
System.loadLibrary(ACWRAPPER);
logger.info("DLL is loaded from memory");
} catch (UnsatisfiedLinkError e) {
loadFromJar();
}
}

/**
* When packaged into JAR extracts DLLs, places these into
*/
private static void loadFromJar() {
// we need to put both DLLs to temp dir
String path = "AC_" + new Date().getTime();
loadLib(path, ACWRAPPER);
loadLib(path, AAMAPI);
loadLib(path, LIBEAU);
}

/**
* Puts library to temp dir and loads to memory
*/
private static void loadLib(String path, String name) {
name = name + ".dll";
try {
// have to use a stream
InputStream in = ACWrapper.class.getResourceAsStream(LIB_BIN + name);
// always write to different location
File fileOut = new File(System.getProperty("java.io.tmpdir") + "/" + path + LIB_BIN + name);
logger.info("Writing dll to: " + fileOut.getAbsolutePath());
OutputStream out = FileUtils.openOutputStream(fileOut);
IOUtils.copy(in, out);
in.close();
out.close();
System.load(fileOut.toString());
} catch (Exception e) {
throw new ACCoreException("Failed to load required DLL", e);
}
}
// blah-blah - more stuff
}

关于java - 如何制作包含 DLL 文件的 JAR 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1611357/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com