java - 从 Spring Boot 中的资源文件夹中读取文件

标签 java spring spring-boot json-schema-validator

我正在使用 Spring Boot 和 json-schema-validator。我正在尝试从 resources 文件夹中读取一个名为 jsonschema.json 的文件。我尝试了几种不同的方法,但我无法让它工作。这是我的代码。

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("jsonschema.json").getFile());
JsonNode mySchema = JsonLoader.fromFile(file);

这是文件的位置。

enter image description here

在这里我可以看到 classes 文件夹中的文件。

enter image description here

但是当我运行代码时出现以下错误。

jsonSchemaValidator error: java.io.FileNotFoundException: /home/user/Dev/Java/Java%20Programs/SystemRoutines/target/classes/jsonschema.json (No such file or directory)

我在代码中做错了什么?

最佳答案

在花了很多时间试图解决这个问题之后,终于找到了一个可行的解决方案。该解决方案利用了 Spring 的 ResourceUtils。 也应该适用于 json 文件。

感谢 Lokesh Gupta 撰写的精彩页面:Blog

enter image description here

package utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.io.File;


public class Utils {

    private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class.getName());

    public static Properties fetchProperties(){
        Properties properties = new Properties();
        try {
            File file = ResourceUtils.getFile("classpath:application.properties");
            InputStream in = new FileInputStream(file);
            properties.load(in);
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
        return properties;
    }
}

回答一些关于评论的问题:

很确定我使用 java -jar target/image-service-slave-1.0-SNAPSHOT.jar

在 Amazon EC2 上运行了这个

看看我的 github 仓库:https://github.com/johnsanthosh/image-service 找出从 JAR 中运行它的正确方法。

关于java - 从 Spring Boot 中的资源文件夹中读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44399422/

相关文章:

java - 从 RAD 启动 websphere 服务器卡在 "Server server1 open for e-business"

java - 我是否必须将 Controller 拆分为多个端点,这些端点代表更复杂对象的组件的 CRUD 操作?

java - 多个 Spring Boot 应用程序

spring-boot - 当您已经有了应用程序端池时,您还需要 AWS RDS 代理吗?

java - 使用 Joda-Time 获取日期的分钟数

java - 将绘制的圆圈对象添加到 Arraylist

java - 限制用户仅使用 Autowiring 接口(interface)

spring - @Document(collection = "Test") 在 MongoRepository 中不起作用 - Spring 数据 - mongodb

spring-boot - 如何用spring-rabbit配置RabbitMQ连接?

java - 随机 session 失效