0

(The answer given to the suggested Stack question didn't help me reach anything, as I've already imported the resources based on those rules).

I've built a JavaFX Gradle project with IntelliJ.

I'm trying to access a users.xml file, located in my project's resources folder. This is my project's structure:

enter image description here

In my HelloController.java class, I'm trying to access the resource in the following method:

protected void onHelloButtonClick() {
        try {
            ObjectMapper mapper = new XmlMapper();
            String path = getClass().getResource("users.xml").toExternalForm();
            InputStream inputStream = new FileInputStream(new File(path));
            TypeReference<List<User>> typeReference= new TypeReference<List<User>>() {};
            List<User> users = mapper.readValue(inputStream, typeReference);

            for (User u: users) {
                System.out.println(u.getUsername() + "\n" + u.getPassword() + "\n");
            }

        } catch(Exception e) {
            e.printStackTrace();
        }
}

The problem is that I receive an error telling me that the file path is invalid: java.io.FileNotFoundException: Invalid file path

At that point, what I tried to do was printing the path variable and this was the output:

jar:file:///E:/git/demo/build/libs/demo-1.0-SNAPSHOT.jar!/com/example/demo/users.xml

As you can see, my program is looking in some sort of build/libs folder (inside the jar?) for my resource, instead of looking at the build/resources folder, where my .xml file was copied.

enter image description here

What may be the problem?

Mario Mateaș
  • 638
  • 7
  • 25
  • 3
    _I've already imported the resources based on those rules_ no, you didn't - you are trying to access the resource with file system api and that's __wrong__ as the duplicate clearly points out ;) – kleopatra May 01 '22 at 12:35
  • 1
    As already pointed out, it is a resource not a file. If you want it as a Stream, then call [getResourceAsStream](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Class.html#getResourceAsStream(java.lang.String)). If you still have issues refer to troubleshooting in the duplicate. Your misunderstanding may be in thinking the resource at runtime would be picked up from your build source resource folder rather than inside your built and deployed package (jar file), which is what actually happens. – jewelsea May 01 '22 at 21:38

0 Answers0