gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 19:39:42 24 4
gpt4 key购买 nike

我有一个 .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 文件中,您可以尝试使用 ClassLoader#getResourceAsStream 将它们作为资源进行评估。并将它们作为二进制文件写入硬盘驱动器上的任何位置。

下面是一些示例代码:

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

关于java - 如何从当前运行的 jar 中复制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17745788/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com