java java.io.FileNotFoundException 当文件存在时

java java.io.FileNotFoundException when file exist

我需要读取 JSON 文件并将其转换为 Java ArrayList,我有代码:

public void loadConfig() {
List<ConfigModel> configModels = JsonUtils.fromFileToList(ConfigReaderService.class.getClassLoader().getResource(ConfigFileName).getPath(), new TypeReference<List<ConfigModel>>() {
        });
}
public static <T> List<T> fromFileToList(String fileName, TypeReference<List<T>> typeReference) {
        try {
            File f = new File(fileName);

            return jsonMapper.readValue(f, typeReference);
        } catch (IOException e) {
            throw new IllegalStateException("can't convert String to Object", e);
        }
    }

当我在 run/debug 中使用 idea 启动应用程序时它工作得很好,但是当我构建 spring-boot jar 应用程序并通过 cmd/bash 执行它时它抛出异常.

java -jar service.jar


  .   ____          _            __ _ _
 /\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.3)

2022-02-11 16:37:59.582 sid: [main] INFO - Starting ServiceApplication v0.0.1-SNAPSHOT using Java 1.8.0_291 on ! with PID 8780 ()
2022-02-11 16:37:59.582 sid: [main] INFO  g.n.w.ServiceApplication - No active profile set, falling back to default profiles: default
2022-02-11 16:38:01.737 sid: [main] ERROR g.n.ws.service.ConfigService - Exception in ConfigService
java.lang.IllegalStateException: can't convert String to Object
        at utils.JsonUtils.fromFileToList(JsonUtils.java:86)
Caused by: java.io.FileNotFoundException: file:\D:\IdeaProjects\service\target\service.jar!\BOOT-INF\classes!\config.json (The filename, directory name, or volume label syntax is incorrect)
        at java.io.FileInputStream.open0(Native Method)
        at java.io.FileInputStream.open(Unknown Source)
        at java.io.FileInputStream.<init>(Unknown Source)
        at com.fasterxml.jackson.core.JsonFactory.createParser(JsonFactory.java:1029)
        at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3514)
        at utils.JsonUtils.fromFileToList(JsonUtils.java:84)
        ... 49 common frames omitted

我哪里错了?

getResourceAsStream() 解决了这个问题