Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - java.io.File with Classpath

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?

like image 878
gtx911 Avatar asked Dec 03 '25 14:12

gtx911


1 Answers

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

like image 133
rjeeb Avatar answered Dec 05 '25 04:12

rjeeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!