如何从当前运行的 jar 文件中复制文件 [英] How to copy files out of the currently running jar

查看:58
本文介绍了如何从当前运行的 jar 文件中复制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a .jar that has two .dll files that it is dependent on. I would like to know if there is any way for me to copy these files from within the .jar to a users temp folder at runtime. here is the current code that I have (edited to just one .dll load to reduce question size):

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 中检索路径的方法都会有所帮助.

My main problem is getting the .dll files out of the jar at runtime. Any way to retrieve the path from within the .jar would be helpful.

提前致谢.

推荐答案

由于您的 dll 捆绑在您的 jar 文件中,您可以尝试使用 ClassLoader#getResourceAsStream 并将它们作为二进制文件写入任何地方想要在硬盘上.

Since your dlls are bundeled inside your jar file you could just try to acasses them as resources using ClassLoader#getResourceAsStream and write them as binary files any where you want on the hard drive.

这是一些示例代码:

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);
    }
}

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

The code above will extract the dll located in the package some.pack.age to the current working directory.

这篇关于如何从当前运行的 jar 文件中复制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆