Java - 将 jar 中的 dll 文件写入硬盘?

标签 java dll file-io jar java-native-interface

我有一个已签名的小程序,我想写出包含在我启动小程序的 jar 中的 dll 文件。

我这样做是因为我想在 dll 上执行 System.load,显然您不能从 applet 的 jar 中加载 DLL。

第二个问题是您是否可以在小程序中添加环境变量 - 例如我想将我的 DLL 提取到硬盘驱动器的某个位置并添加环境变量以便 System.load 可以找到它。

最佳答案

您应该能够通过以下方式完成此操作:

  1. 从小程序 jar 中提取 .dll 到系统临时目录。
  2. 使用 AccessController 在提取的文件上调用 System.load(..)

这种方法将避免设置环境变量的需要。下面是一些示例代码:

AccessController.doPrivileged(new PrivilegedAction<Void>() {
    public Void run() {
        String dllName = "my.dll";
        File tmpDir = new File(System.getProperty("java.io.tmpdir"));
        File tmpFile = new File(tmpDir, dllName);

        try {
            InputStream in = getClass().getResourceAsStream(dllName);
            OutputStream out = new FileOutputStream(tmpFile);

            byte[] buf = new byte[8192];
            int len;
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
            }

            in.close();
            out.close();

            System.load(tmpFile.getAbsolutePath());

        } catch (Exception e) {
            // deal with exception
        }

        return null;
    }
});

关于Java - 将 jar 中的 dll 文件写入硬盘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5496400/

相关文章:

javascript - 使用 JavaScript 访问 DLL

c - 避免蒙特卡罗模拟中的基本 rand() 偏差?

python - 写锁定文件有时找不到内容(打开 pickled pandas DataFrame 时)- EOFError : Ran out of input

java - 找不到元素 'ehcache' 的声明

java - 从十六进制转换为字节

javascript - 差异时区浏览器和 Java

c# - 从 C# 传递到非托管 dll 后参数不正确

java - 数组垂直显示而不是水平显示

java.io.IOException : The handle is invalid

csv - 在 hadoop 应用程序中读写 CSV 文件