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?

gtx911
  • 1,189
  • 4
  • 25
  • 46
  • try ``ClassLoader.getSystemResource("/demo/test.txt")`` (with a slash at the beginning) – spi Feb 19 '19 at 12:30
  • The same error @spi – gtx911 Feb 19 '19 at 12:31
  • 1
    ``URL url = getClass().getResource("/demo/test.txt")`` – spi Feb 19 '19 at 12:32
  • from the [documentation](https://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html#getSystemResource(java.lang.String)) 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() – Federico Ciuffardi Feb 19 '19 at 12:32
  • Just a hint: `C:/javaproject/src/main/resources/demo/test.txt` is **not** a relative path. – bkis Feb 19 '19 at 12:44

1 Answers1

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()

rjeeb
  • 461
  • 3
  • 11