有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVA尼奥。文件FileSystemNotFoundException与spring应用程序jar

我有一个spring boot应用程序,它依赖于另一个jar,比如a。a需要bean中的一些文件,比如MyBean。所以我把这些文件放在项目的resources文件夹中,通过bean的构造函数中的以下代码,我获得了它们的路径,然后将其设置到A的bean中

URL res = this.getClass().getClassLoader().getResource("fileNeededByMyBean.dat");
File file = Paths.get(res.toURI()).toFile();
String absolutePath = file.getAbsolutePath();
....use absolutePath in bean....

在像IntelliJ这样的IDE中,项目运行良好。但当我尝试使用java-jar应用程序启动它时。jar命令失败,出现错误:

nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [x.y.z.MyBean]: Constructor threw exception; nested exception is java.nio.file.FileSystemNotFoundException

如何让它工作


共 (1) 个答案

  1. # 1 楼答案

    Jar文件本质上是zip存档。java不能将zip归档文件中的项目视为文件
    要读取资源表单jar文件,请使用: this.getClass().getClassLoader().getResourceAsStream("fileNeededByMyBean.dat");
    将资源中的数据写入临时文件,然后使用其绝对路径