I am trying to enumerate classes in the package with
Enumeration<URL> resourceUrls = myObject.getClassLoader().getResources("path/to/my/package/");
while (resourceUrls.hasMoreElements()) {
...
Unfortunately it returns nothing. Why?
Assuming path is correct. Path starts with no slash and ends with slash. There are several public classes under path.to.my.package package.
I took this code from Spring.
You cannot walk a class path like you can walk a file path. Walking a file path is done on the file system, which does not apply to a class path.
While a java class path entries are formed like file paths and usually are folders and files (either on the file system or inside a JAR archive), it does not necessarily have to be that way. In fact, the classes of one single package may originate from various locations of differing nature: one might be loaded from a local JAR file while another one might be loaded from a remote URL.
The method ClassLoader.getResources() exists to provide access to all "occurrences" of a resource if it has the same name in different JAR files (or other locations). For example you can use
ClassLoader.getSystemClassLoader().getResources("META-INF/MANIFEST.MF");
to access the manifest file of each JAR file in your class path.
Try with
Enumeration<URL> urls = ClassLoader.getSystemClassLoader().getResources("path/to/my/package");
while (urls.hasMoreElements()) {
System.out.println(urls.nextElement());
}
Related
I'm trying to export a .JAR to be used as library to other projects. The problem is that I need to use relative paths when referencing files inside this library, but the only solutions I found were using absolute paths like:
private static final String FILE = new File("").getAbsolutePath().concat("/src/bla/file.txt");
Obviously whenever I try to run this line of code as an exported library I'll get something like DRIVE/project/src/bla/file.txt which is not correct since this .JAR can be anywhere inside DRIVE/projects like DRIVE/projects/lib/myLib.jar.
In Nodejs we had easy functions to retrieve relative paths according to the runtime location. How can I reference files in such a way that it will capture the "runtime path" so that I can safely reference them and the path will be dynamically solved?
For those who are so eager to mark this question as duplicate, please read with attention first. I'm NOT asking how to READ files from resources!
To use the "file.txt" present in the classpath,we need to make sure the "file.txt" is present in the directory represented by classpath.
Assume you have all the class files generated in a directory named "/home/abcuser/target".
For simplicity we will place the file.txt in the target directory root level.
The main class is say TestFileAccess.class(the class with the main method)
To execute the main class present in the target directory you can use the below command
java -cp /home/abcuser/target TestFileAccess
Now, the classpath in this case is /home/abcuser/target
To access the resources on classpath,you can go with two ways.
ClassLoader.getSystemResource and ClassLoader.getSystemResourceAsStream methods.
Class.getResource and Class.getResourceAsStream
The main difference between the ClassLoader and Class versions of the methods is in the way that relative paths are interpreted.
The Class methods resolve a relative path in the "directory" that corresponds to the classes package.
The ClassLoader methods treat relative paths as if they were absolute; i.e. the resolve them in the "root directory" of the classpath
Using ClassLoader you can use the below snippet
InputStream inputStream = ClassLoader.getSystemResourceAsStream("file.txt");
To explicitly reference a resource as a classpath file you can add the resource path to the classpath while executing the java code.
Let's say your resource "file.txt" is in /home/abcuser/resources.
You can add the the resource path to the classpath during the java execution start as shown below
java -cp "/home/abcuser/target:/home/abcuser/resources" TestFileAccess
I have a maven project with these standard directory structures:
src/main/java
src/main/java/pdf/Pdf.java
src/test/resources
src/test/resources/files/x.pdf
In my Pdf.java,
File file = new File("../../../test/resources/files/x.pdf");
Why does it report "No such file or dirctory"? The relative path should work. Right?
Relative paths work relative to the current working directory. Maven does not set it, so it is inherited from whatever value it had in the Java process your code is executing in.
The only reliable way is to figure it out in your own code. Depending on how you do things, there are several ways to do so. See How to get the real path of Java application at runtime? for suggestions. You are most likely looking at this.getClass().getProtectionDomain().getCodeSource().getLocation() and then you know where the class file is and can navigate relative to that.
Why does it report "No such file or dirctory"? The relative path should work. Right?
wrong.
Your classes are compiled to $PROJECT_ROOT/target/classes
and your resources are copied to the same folder keeping their relative paths below src/main/resources.
The file will be located relative to the classpath of which the root is $PROJECT_ROOT/target/classes. Therefore you have to write in your Pdf.java:
File file = new File("/files/x.pdf");
Your relative path will be evaluated from the projects current working directory which is $PROJECT_ROOT (AFAIR).
But it does not matter because you want that to work in your final application and not only in your build environment. Therefore you should access the file with getClass().getResource("/path/to/file/within/classpath") which searches the file in the class path of which the root is $PROJECT_ROOT/target/classes.
No the way you are referencing the files is according to your file system. Java knows about the classpath not the file system if you want to reference something like that you have to use the fully qualified name of the file.
Also I do not know if File constructor works with the classpath since it's an abstraction to manage the file system it will depend where the application is run from. Say it is run from the target directory at the same level as source in that case you have to go one directory up and then on src then test the resources the files and finally in x.pdf.
Since you are using a resources folder I think you want the file to be on the classpath and then you can load a resource with:
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("<path in classpath>");
Then you can create a FileInputStream or something to wrap around the file. Otherwise use the fully qualiefied name and put it somewere like /home/{user}/files/x.pdf.
Problem statement:
I have a jar file with a set of configuration files in a package mycompany/configuration/file/.
I don't know the file names.
My intention is to load the file names at runtime from the jar file in which they are packaged and then use it in my application.
As far as I understood:
When I use the ClassLoader.getResources("mycompany/configuration/file/") I should be getting all the configuration files as URLs.
However, this is what is happening:
I get one URL object with URL like jar:file:/C:/myJarName.jar!mycompany/configuration/file/
Could you please let me know what I am doing wrong ?
For what you are trying to do I don't think it is possible.
getResource and getResources are about finding named resources within the classloader's classpath, not listing values beneath a directory or folder.
So for example ClassLoader.getResources("mycompany/configuration/file/Config.cfg") would return all the files named Config.cfg that existed in the mycompany/configuration/file path within the class loader's class path (I find this especially useful for loading version information personally).
In your case I think you might almost have half a solution. The URL you are getting back contains the source jar file (jar:file:/C:/myJarName.jar). You could use this information to crack open the jar file a read a listing of the entries, filtering those entries whose name starts with "mycompany/configuration/file/".
From there, you could then fall back on the getResource method to load a reference to each one (now that you have the name and path)
I have a project where I'm compiling files to locations relative to getClass().getResource("/"). How can I get File objects for these locations?
When I try getClass().getResource("/nonExisting"), they return null. How can I resolve the paths?
There's no reason to expect existent resources to be normal files; they could be buried inside a jar-file somewhere on your classpath.
With non-existent resources, the situation is even worse; even if you could guarantee in the abstract that it is a non-existent normal file, it could be a non-existent normal file in any of the top-level directories in your classpath; there's no sensible way to decide which directory it would have been in, had it existed. (For example, if your classpath contains both classes and testClasses, then /nonExisting could be either classes/nonExisting or testClasses/nonExisting.)
I want to load a resource with this:
InputStream iStream = Config.class.getResourceAsStream("autopublisherpath.cfg");
So I set the CLASSPATH to make it work. This is my dir hierarchy:
- autopublisher
.classes
.lib
.resources
If I add %AUTOPUBLISHER_HOME%\resources\config to my classpath I cannot get the resource. Otherwise if I put my .cfg file in classes and add %AUTOPUBLISHER_HOME%\classes the resource is loaded properly. The classes dir doesn't contain anything other than the autopublisherpath.cfg.
Ultimately I want to call:
java com.test.Something
Where something is loading the resource. The thing is I want user to modify this config file so I do not include it inside my jar packaging.
Am I not understanding the CLASSPATH correctly?
thank you
One thing to pay attention to when using getResourceAsStream is the format of the resource name that you are retrieving. By default if you do not specify a path, e.g., "autopublisherpath.cfg", the classloader will expect that the resource being specified is within the same package as the Class on which you executed the getResourcesAsStream method. The reason for this behavior can be found in the JVM documentation for getResourceAsStream:
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form: modified_package_name/name
In your particular example, if the Config class was located in the com.test.config package, then the resource name of "autopublisherpath.cfg" would be converted to "/com/test/config/autopublisherpath.cfg" (period in package is replaced with a '/' character). As a result, keeping with your original project hierarchy, you would need to place the file into the location:
autopublisher/resources/config/com/test/config
where autopublisher/resources/config was added as part of application's execution classpath.
If you are looking to add a specific config directory to your classpath and want the file to be located in the root of that directory, then you need to prefix the name of the file with a '/' character, which specifies that the resource should be in the root package of the classpath.
InputStream iStream = Config.class.getResourceAsStream("/autopublisherpath.cfg");
Using this code, you should be able to add the resource/config directory to your classpath and read the file as expected.
On a side note, the getResourceAsStream method loads the resource using the Classloader of the class from which it was executed (in this case Config). Unless your application uses multiple class loaders, you can perform the same function from any of your class instances using this.getClass().getResourceAsStream(...).