gpt4 book ai didi

java - 如何在 URLClassLoader 中加载存储在应用程序资源中的 JAR

转载 作者:行者123 更新时间:2023-11-30 10:39:21 26 4
gpt4 key购买 nike

我试图在 URLClassLoader 中加载 JAR 文件。这个 JAR 文件存储在我的项目的资源中,当我使用 maven 运行我的项目时,它可以正常使用以下代码:

new URLClassLoader(
new URL[]{MyClass.class.getClassLoader().getResource("dependencies/dependency.jar")},
ClassLoader.getSystemClassLoader().getParent()
);

但是,当我使用 mvn clean install 构建项目然后尝试使用 java -jar myapp.jar 运行生成的 JAR 时,它看起来像 dependency.jar 未加载。 dependency.jar 文件正确存储在 dependencies/dependency.jar 下的项目 JAR 中,但未被读取。

我假设它不能从 JAR 文件中加载,但它们是解决方法吗?

我认为一个解决方案是使用 getResourceAsStream,但我需要将此流转换为 URL。

如果可能的话,我想使用一种不涉及为存储 dependency.jar 的内容而创建的临时文件的解决方案。

最佳答案

我认为您的问题是由于它无法读取 zip 中的 zip,因此您应该将 jar 文件复制到一个临时文件中并将此临时文件提供给您的 URLClassLoader 如下:

// Get the URL of my jar file
URL url = MyClass.class.getResource("/dependencies/dependency.jar");
// Create my temporary file
Path path = Files.createTempFile("dependency", "jar");
// Delete the file on exit
path.toFile().deleteOnExit();
// Copy the content of my jar into the temporary file
try (InputStream is = url.openStream()) {
Files.copy(is, path, StandardCopyOption.REPLACE_EXISTING);
}
// Create my CL with this new URL
URLClassLoader myCL = new URLClassLoader(
new URL[]{path.toUri().toURL()}, ClassLoader.getSystemClassLoader().getParent()
);

关于java - 如何在 URLClassLoader 中加载存储在应用程序资源中的 JAR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39327757/

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