gpt4 book ai didi

java - 使用 JAR 中的文件,同时从 jar 运行应用程序

转载 作者:行者123 更新时间:2023-12-01 17:37:21 24 4
gpt4 key购买 nike

当将应用程序作为 JAR 运行时,我尝试使用文件。当我通过 Intelij 运行应用程序时,一切都很好。但是,当我尝试通过 jar 运行它时,我无法访问该文件。我尝试阅读一些包含类似内容的主题,但没有一个有帮助(如 Reading a resource file from within jarHow do I read a resource file from a Java jar file?)这是我的目标树和资源:enter image description here enter image description here

当我使用时

String path = String
.join("", "classpath:static\assets\config\", fileName);
File file = ResourceUtils.getFile(path);
InputStream targetStream = new FileInputStream(file)

在 intelij run 期间,一切正常。

对于 jar,我尝试过:

String path = String
.join("", "static\assets\config\", fileName).replace("\\","/")).toExternalForm();
String path2 = String
.join("", "static\assets\config\", fileName).replace("\\","/")).getFile();
String path3 = String
.join("", "static\assets\config\", fileName).replace("\\","/")).getPath();

还有许多其他。它们会产生正确的路径,例如:

  • file:/D:/Projects/myProject/target/classes/static/assets/config/fileName(如果是 toExternalForm)

  • /D:/Projects/myProject/target/classes/static/assets/config/fileName(如果是 getFile)

    但是,当我尝试时,它们都会导致 null InputStream:

 InputStream in = getClass().getResourceAsStream(everyPath);

我收到一个错误:java.io.FileNotFoundException: D:\Projects\myProject\target\project-app-1.0.jar\BOOT-INF\classes\static\assets\config\fileName (系统找不到指定的路径)当我用7zip打开project-app-1.0.jar时,它的路径是:D:\Projects\myProject\target\project-app-1.0.jar\BOOT-INF\classes\static\assets\config\fileName

这就是我的资源处理程序的样子:

  private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/resources/", "classpath:/static/"};
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(
CLASSPATH_RESOURCE_LOCATIONS);
}

最佳答案

当您想使用 jar 中的某些内容时,请忘记"file",它只是一个简单的“资源”,您必须与 getResource 一起使用。

如果您使用标准打包系统,“resources”文件夹中的所有内容都放在 JAR 的根目录下,因此如果您想读取“static\assets\config\”文件夹中的“foo.txt”文件,您可以必须做的使用方法:

InputStream in = ClassLoader.getSystemResourceAsStream("static/assets/config/foo.txt");

关于java - 使用 JAR 中的文件,同时从 jar 运行应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61015318/

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