3

I need to use/define a java.io.File variable type to get a file that is going to be send as parameter to another method.

Now I have with relative path:

File file = new File("C:/javaproject/src/main/resources/demo/test.txt");

I want to change it using ClassLoader like this:

ClassLoader.getSystemResource("/demo/test.txt");

But I cannot use it into File because is not the same type. If I use .toString() it returns NullPointerException:

java.lang.NullPointerException: null

And when I print it with a System output return the same, an exception: System.out.println(ClassLoader.getSystemResource("demo/test.txt").toString());

Both, folder and file exists. Why that error?

5
  • try ClassLoader.getSystemResource("/demo/test.txt") (with a slash at the beginning) Commented Feb 19, 2019 at 12:30
  • The same error @spi Commented Feb 19, 2019 at 12:31
  • 1
    URL url = getClass().getResource("/demo/test.txt") Commented Feb 19, 2019 at 12:32
  • from the documentation it returns a URL object for reading the resource, or null if the resource could not be found. So you are inputing a wrong "name" so it's returning null causing the NullPointerException when you try to do null.toString() Commented Feb 19, 2019 at 12:32
  • Just a hint: C:/javaproject/src/main/resources/demo/test.txt is not a relative path. Commented Feb 19, 2019 at 12:44

1 Answer 1

6

You can do this:

try {
    URL resource = getClass().getClassLoader().getResource("demo/test.txt");
    if (nonNull(resource)) {
        File file = new File(resource.toURI());
        // do something
    }
} catch (URISyntaxException e) {
    LOGGER.error("Error while reading file", e);
}

This answer shows the different between ClassLoader.getSystemResource and getClassLoader().getResource()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.