【问题标题】:FileNotFoundException while getting file from resources folder using getResource()使用 getResource() 从资源文件夹获取文件时出现 FileNotFoundException
【发布时间】:2020-06-19 12:22:51
【问题描述】:

我需要从 File 对象中的资源文件夹中获取此文件,而不是在 InputSream 中。 我正在使用以下代码,在 Eclipse 上工作文件,但在服务器上使用 FoleNotFoundException。 )使用 AWS EC2)

代码:

    URL res = ResidentHelperService.class.getClassLoader().getResource("key.pem");
                System.out.println("resource path2  :" + res);          
    File privateKeyFile = Paths.get(res.toURI()).toFile();

打印后的路径如下:

:jar:file:/home/centos/myproject/microservices/user-service/target/user-service-0.0.1-SNAPSHOT.jar!/BOOT-INF/lib/project-common-utility-0.0。 1-SNAPSHOT.jar!/key.pem

我在用户服务 pom 中添加了对公共 jar 的依赖。

请帮我从公共项目的资源中获取文件。

【问题讨论】:

    标签: java spring-boot maven


    【解决方案1】:

    如果您的文件位于 resources 文件夹中,从代码中访问它的最简单方法可能是使用 Spring 提供的 org.springframework.util.ResourceUtils 类:

    try {
        final File file = ResourceUtils.getFile("classpath:key.pem");
        ....
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    

    也许这种方式可以帮助您解决问题。

    【讨论】:

      猜你喜欢
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 2019-03-26
      • 1970-01-01
      • 2019-03-24
      • 2011-02-05
      相关资源
      最近更新 更多