Home > Enterprise >  java java.io.FileNotFoundException when file exist
java java.io.FileNotFoundException when file exist

Time:02-14

I need to read JSON file and cast it to Java ArrayList, i have code:

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);
        }
    }

It's perfectly working when i'm starting application with idea in run/debug, but it throws exception when i'm building spring-boot jar application and execution it via 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

where my mistake?

CodePudding user response:

getResourceAsStream() fixed this problem

  • Related