【问题标题】:Load file from folder spring boot从文件夹spring boot加载文件
【发布时间】:2019-02-26 10:13:59
【问题描述】:

Apache Maven 3.5.4

jdk-10.0.1

Spring Boot 2.0.4.RELEASE

赢 10

我在 src/main/resources/images/ 文件夹中有图像。当我在 intelli J 中运行应用程序时,它工作正常,但是当我创建应用程序的 jar 时。它找不到图像文件。我试过以下都没有奏效。知道如何检索图像文件吗?谢谢。

    dogImageFile = new File("src/main/resources/images/dog.png");
    dogClick = new Image(dogImageFile.toURI().toString());


    dogImageFile = new File("\\images\\dog.png");
    dogClick = new Image(dogImageFile.toURI().toString());


    //Tried via @Value("classpath:dog.png") and ResourceLoader 

    //Also tried 

    dogClick= new Image(getClass().getClassLoader().getResource("src/main/resources/images/dog.png").toString(), true);

【问题讨论】:

    标签: java maven spring-boot classloader


    【解决方案1】:

    这与java的版本和springboot的版本无关。您需要关心编译后的类文件和资源文件的路径。

    【讨论】:

    • InputStream input = null; // read from the root folder input = this.getClass().getResourceAsStream("/images/dog.png");
    【解决方案2】:
    InputStream stream = getClass().getClassLoader().getResourceAsStream("static/xxx.pdf");
    File targetFile = new File("xxx.pdf");
    FileUtils.copyInputStreamToFile(stream, targetFile);
    

    您好,您可以使用此代码读取 jar 中的文件!

    【讨论】:

      【解决方案3】:

      这样就可以了。

      dogClick = new Image("/images/dog.png");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-02
        • 2017-04-25
        • 1970-01-01
        • 2016-04-06
        • 2017-02-05
        • 2017-11-17
        • 1970-01-01
        • 2017-02-25
        相关资源
        最近更新 更多