如何从当前运行的 jar 中复制文件

2024-04-12

我有一个 .jar,它有两个依赖的 .dll 文件。我想知道是否有任何方法可以在运行时将这些文件从 .jar 复制到用户临时文件夹中。这是我当前的代码(编辑为仅加载一个 .dll 以减少问题大小):

public String tempDir = System.getProperty("java.io.tmpdir");
public String workingDir = dllInstall.class.getProtectionDomain().getCodeSource().getLocation().getPath();

public boolean installDLL() throws UnsupportedEncodingException {

try {
             String decodedPath = URLDecoder.decode(workingDir, "UTF-8");
             InputStream fileInStream = null;
             OutputStream fileOutStream = null;

             File fileIn = new File(decodedPath + "\\loadAtRuntime.dll");
             File fileOut = new File(tempDir + "loadAtRuntime.dll");

             fileInStream = new FileInputStream(fileIn);
             fileOutStream = new FileOutputStream(fileOut);

             byte[] bufferJNI = new byte[8192000013370000];
             int lengthFileIn;

             while ((lengthFileIn = fileInStream.read(bufferJNI)) > 0) {
                fileOutStream.write(bufferJNI, 0, lengthFileIn);
             }

            //close all steams
        } catch (IOException e) {
      e.printStackTrace();
             return false;
        } catch (UnsupportedEncodingException e) {
             System.out.println(e);
              return false;
        }

我的主要问题是在运行时从 jar 中获取 .dll 文件。任何从 .jar 中检索路径的方法都会有所帮助。

提前致谢。


由于您的 dll 捆绑在您的 jar 文件中,您可以尝试使用以下命令将它们视为资源类加载器#getResourceAsStream http://docs.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getResourceAsStream%28java.lang.String%29并将它们作为二进制文件写入硬盘上任何您想要的位置。

这是一些示例代码:

InputStream ddlStream = <SomeClassInsideTheSameJar>.class
    .getClassLoader().getResourceAsStream("some/pack/age/somelib.dll");

try (FileOutputStream fos = new FileOutputStream("somelib.dll");){
    byte[] buf = new byte[2048];
    int r;
    while(-1 != (r = ddlStream.read(buf))) {
        fos.write(buf, 0, r);
    }
}

上面的代码将提取位于包中的dllsome.pack.age到当前工作目录。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从当前运行的 jar 中复制文件 的相关文章

随机推荐