简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM