Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.nio.file.Path for a classpath resource

Tags:

java

java-7

nio2

Is there an API to get a classpath resource (e.g. what I'd get from Class.getResource(String)) as a java.nio.file.Path? Ideally, I'd like to use the fancy new Path APIs with classpath resources.

like image 968
Louis Wasserman Avatar asked Oct 11 '22 08:10

Louis Wasserman


People also ask

What is Java NIO file paths?

Technically in terms of Java, Path is an interface which is introduced in Java NIO file package during Java version 7,and is the representation of location in particular file system.As path interface is in Java NIO package so it get its qualified name as java. nio. file.

How do I load resources from classpath?

We can either load the file(present in resources folder) as inputstream or URL format and then perform operations on them. So basically two methods named: getResource() and getResourceAsStream() are used to load the resources from the classpath. These methods generally return the URL's and input streams respectively.

How do I view the resources folder in a jar file?

This works when running inside and outside of a Jar file. PathMatchingResourcePatternResolver r = new PathMatchingResourcePatternResolver(); Resource[] resources = r. getResources("/myfolder/*"); Then you can access the data using getInputStream and the filename from getFilename .


1 Answers

This one works for me:

return Path.of(ClassLoader.getSystemResource(resourceName).toURI());
like image 243
keyoxy Avatar answered Oct 18 '22 03:10

keyoxy