【问题标题】:How to copy files out of the currently running jar如何从当前运行的 jar 中复制文件
【发布时间】:2013-07-18 17:18:47
【问题描述】:

我有一个 .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 中检索路径的任何方法都会有所帮助。

提前致谢。

【问题讨论】:

  • 是否要获取arround .dll文件的路径
  • 是的,这样我就可以访问文件并复制它们。我需要的只是类路径。我已经知道如何复制文件了。

标签: java jar executable-jar


【解决方案1】:

由于您的 dll 捆绑在您的 jar 文件中,您可以尝试使用 ClassLoader#getResourceAsStream 将它们作为资源进行 acasses,然后将它们作为二进制文件写入硬盘驱动器上的任何位置。

这里是一些示例代码:

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解压到当前工作目录。

【讨论】:

  • +1 例如代码。谢谢。现在只需稍作调整即可完美运行。
  • 我想你的意思是:你是* ;)
  • 我不会读两次,而是读一次。 while(r = ddlStream.read(buf) != -1) { fos.write(buf, 0, r); }
【解决方案2】:

使用能够在此 JAR 文件中定位资源的类加载器。您可以按照 Peter Lawrey 的建议使用类的类加载器,也可以使用指向该 JAR 的 URL 创建一个 URLClassLoader

一旦你有了那个类加载器,你就可以用ClassLoader.getResourceAsStream 检索一个字节输入流。另一方面,您只需为要创建的文件创建一个FileOutputStream

最后一步是将所有字节从输入流复制到输出流,就像您在代码示例中所做的那样。

【讨论】:

    【解决方案3】:

    使用myClass.getClassLoader().getResourceAsStream("loadAtRuntime.dll");,您将能够在 JAR 中找到并复制 DLL。您应该选择一个也将在同一个 JAR 中的类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-30
      • 2023-03-10
      • 1970-01-01
      • 2012-07-13
      • 2011-02-19
      • 2011-10-04
      • 2017-06-14
      相关资源
      最近更新 更多