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

我有一个.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; } 

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

提前致谢。

由于您的dll在jar文件中是可靠的,因此您可以尝试使用ClassLoader#getResourceAsStream将它们作为资源进行处理,并将它们作为二进制文件写入硬盘上的任何位置。

以下是一些示例代码:

 InputStream ddlStream = .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到当前工作目录。

使用能够在此JAR文件中查找资源的类加载器。 您可以使用Peter Lawrey建议的类的类加载器,或者您也可以使用该JAR的URL创建URLClassLoader

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

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

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