getClass().getResource() always returning null - java

I am trying to set the URL of an image that is located in my resource folder in my src folder. It is always setting the URL to null. The image is there and everything is named correctly. What is the issue? Thanks!
My file structure:
sp1
src
resources
01.png
Here is my code where I am trying to set the URL for the picture:
this.setImagePath(getClass().getResource("/resources/01.png"));
And the setImagePath is doing this, I am sure this is not the problem, because I followed the execution and it is setting it equal to null.
public final void setImagePath(URL imagePath) {
this.imagePath = imagePath;
}
Solution
I had to clean the build and rebuild. It worked after that fix.

I had to clean the build and then rebuild. Works now.

You need to check that, however you're building, the image file gets copied over to wherever the class files are compiled to. I.e. if your class is com.foo.MyImageLoader and located at <build dir>/com/foo/MyImageLoader.class, then the image should be at <build dir>/resources/01.png for you to be able to load it like that.

make sure the resource file is under your class path. For example, check whether your module/project is compiled to xxx.jar and saved under folder "target"
I had this problem as well, when I run mvn install, there is NO jar file generated, that's why no resource found in jar file in target
The cause of no jar generated is caused by following config in pom.xml, remove it and rerun install would be fine.
<packaging>pom</packaging>

If using JDeveloper, make sure that you have the extension of the file that you want copied to the classes folder for use selected. Right click on the project and choose project properties to get to this screen.

I would guess the URL should be "01.png" not "/resources/01.png"

Related

Can not find file that is in resource folder - java

I have a question regarding file handling.
I automate a page using selenium, and I need to upload a file in this page.
I want to put the file in resource folder and read it's path in the test (since many OS and path will be different to any computer WIN/MAC).
I put the file manually in the resource folder, and it put it in:
X:\Project_11_01_2021\src\test\resources
when I used the ClassLoader and try to find the file it not found it,
I saw that if I manually put it in this path it find it, found.
X:\Project_11_01_2021\out\test\resources
the problem is that I am using git and if I add to the resources it upload to git and every one will get the change, and when I put in out\test\resources it is not displayed in the source tree to commit to git.
is their a way that classLoader will search in the first location? and not in the second?
[][path that worked]
[][when here not worked]
/******* test *******/
public void entertax() throws Exception {
WebDriver deiver2 = getWebDriver();
Thread.sleep(1000);
ClassLoader classLoader = getClass().getClassLoader();
String path = classLoader.getResource("TAX12.pdf").getPath();
System.out.println("\n\n path is " + path);
deiver2.switchTo()
.activeElement();
deiver2.findElement(By.xpath("//input[#type='file']"))
.sendKeys(
"X:\\Project_11_01_2021\\out\\test\\resources\\fw8TAX12.pdf");
System.out.println("END");
}
This issue looks more like an IDE configuration problem.
Your code classLoader.getResource("TAX12.pdf") looks correct (1. using classLoader.getResource() method && 2. specifying the correct relative path within the resources folder).
I assume why the code fails to find the file is due to the fact that the resources folder is not part of your applications classpath (I'm assuming your trying to run the code from your IDE which apparently seems to be IntelliJ).
I'm not regularly using IntelliJ, but you can specify the classpath settings in the Module settings.
In the Module settings specify the resources folder as a resource:
When successfully added the resources folder to the classpath it should display an icon like this in the project explorer:
After adding the resources folder to your classpath everything should work.
EDIT:
In case you're using Maven also make sure to specify the resources folder as such in the pom.xml file correspondingly.
Also make sure to spell the name of the file you're looking for "TAX12.pdf" correctly, since it seems to differ in your code and in your screenshots (not sure if it differs only because posting it here or also in your real code base).

UrlClassLoader to load a image resource

I am creating an eclipse workspace starting by a java project (not written by me).
I am facing problems with the following method:
public static URL getURL(String fileName) {
URLClassLoader urlLoader = (URLClassLoader) getInstance().getClass()
.getClassLoader();
URL fileLocation = urlLoader.findResource(fileName);
return fileLocation;
since the findResource doesn't find the JPG resource (filename = "icons/INIT.JPG").
Looking on urlLoader.getUrl, I noticed the class aims only to jar files. Adding the folder icon to the Project->Libraries under eclipse I managed to let findResources look into the icon folder: nevertheless, the image is not a jar file and so it isn't considered.
Honestly, I don't get the point of using this process to load an image, but I cannot change the code and I was hoping in a solution within Eclipse project setup.
Thanks in advance
Based on the answers to my questions in the original comment, there are some facts:
You cannot change the code, and it looks like it's retrieving the AppClassLoader.
Even if you cast it into URLClassLoader, it's still an instance of an AppClassLoader, so it will look for the contents of the classpath and all JAR/ZIP files in JAVA_HOME\lib\ext.
You said that the project is guaranteed to work without to move the file anywhere, so there's only one option: add the file that you want to retrieve with the ClassLoader to the classpath.
Right click on the project, select Build Path and choose Configure Build Path.
Click on Source > Add Folder... and add the folder where the resources that you want to take are.
PD: If you add the folder as Class Folder in the Libraries tab, the JPG image won't be recognised by the AppClassLoader.

Why does getResource return null

I'm trying to access a file in my project. But getResource method returns null.
This is how my project looks like:
Thread.currentThread().getContextClassLoader().getResource("assets/xxx.png"); //returns null
And how project folder in eclipse workspace looks like:
Why? I want to access files in my assets folder?
Edit
I created a jar file and this is content of the jar:
Solved
First of all, I've a lot of image files so I want to organize all them in a folder. I put the assets folder in src directory and finally I was able to access the files.
this.getClass().getClassLoader().getResource("assets/xxx.png");
There are lot of ways to add a resource to the jar file, you can put it in src, add as a resource if you use maven, ant etc... If you able to bundle whole directory then you should be able to use your original piece of code.
With the current structure you can use following piece of code.
Thread.currentThread().getContextClassLoader().getResource("/xxx.png").
Try using / prefixing.
Thread.currentThread().getContextClassLoader().getResourceAsStream("/xxx.png")
For someone struggling as me. For Maven just run mvn clean install.
After that Thread.currentThread().getContextClassLoader().getResource() should work.
Is there a reason you're using the the class loader of the current class? Something like this.getClass().getClassLoader().getResource("/xxx.png") should be more reliable.
Use the following code, it should work.
YOUR_CLASS_HERE.class.getClass().getResource( "/xxx.png" );
e.g.
Signin.class.getClass().getResource( "/xxx.png" );
Either Approach will work. its just Filepath issue.
Your Jar Structure shows no "asset" Folder
xxx.png file is directly in Jar File.
Try to remove "assets" from below line of code.
Thread.currentThread().getContextClassLoader().getResource("assets/xxx.png"); //returns null
Also, if you want to use "assets" folder in ur classpath, please ensure that your jar contains "assets" folder.

Java code cannot find resource file after build and clean in Netbeans IDE?

I really need your help to solve my own problem. Now, I'm dealing with small code app. In that project folder contain some resource files (*.xlsx, *.png,...). I placed them in current folder with code file. I just wonder that when I run my code in netbean ide, it just worked find.
After I build code project, I get a jar file in "dist" directory. I run it. It open normally since app used JFrame as user interface. However, when I execute some function of that app, it showed me the error log. Here is the error message:
java.io.FileNotFoundException:
src\sample.xlsx (The system cannot find the path specified)
What's the matter out there?
Here is some pieces of my code:
copyFile(new File("src\\sample.xlsx"),
new File(txtout.getText()+"\\sample.xlsx"));
Node: copyFile function is used for copy file from source to dest.
Here is my project folder structure in Netbean IDE:
Project Name
Source Pakage(src)
myClass.java, sample.xlsx, etc
First, never reference src directly, the directory will not exist once the program is built. Second, you can not access resources which have been embedded within in the application context via a File reference, they simply no longer exist on the file system.
Instead, you need to use Class#getResource or Class#getResourceAsStream
URL url = getClass().getResource("/sample.xlsx");
InputStream is = getClass().getResourceAsStream("/sample.xlsx");
// Don't forget to manage your streams appropriately...
Well you can create a folder named resources under the src folder put your resources in it and use them in your code by using getResourceAsStream() and getResource() methods that can access the embedded resources.Clean and Build will compile the code and embed the contents of the resources folder into the application’s .jar file.
Ways of Accessing resources :
String pathToImage = "resources/images/filling.png";
InputStream stream= ClassName.class.getResourceAsStream(pathToImage );
String pathToImage = "resources/images/filling.png";
InputStream stream= ClassName.class.getResource(pathToImage );
please refer the link information

Opening a xml file from eclipse and from a .jar file in java

Yesterday, I had a problem because I couldn't manage to open a xml file (it owuld give me a FileNotFoundException) located in the ressources folder of my .jar file, which I managed to open on eclipse using the following lines of code. You can see my old problem here. This was my code with the problem :
File xmlFile = new File("ressources/emitter.xml");
ConfigurableEmitter emitter = ParticleIO.loadEmitter(xmlFile);
Someone told me it that one way was to use getClassLoader().getRessourceAsStream method to open a xml file in a .jar file that was exported
InputStream i= this.getClass().getClassLoader().getResourceAsStream("ressources/emitter.xml");
ConfigurableEmitter emitter = ParticleIO.loadEmitter(i);
Unfortunately, that solution only works when I export my project into a .jar file, so if I want to go back debugging my program, I have to take the old code that would only works on eclipse.
My question is: is there any better way to do this without having to change my code if I want to export it or if I want to debug it?
Thank you
edit :
Thank you all, it works perfectly fine now
my problem was that I put my ressources folder like that :
+project
+src
+ressources
+emitter.xml
InputStream i= this.getClass().getClassLoader().getResourceAsStream("/ressources/emitter.xml");
The above should work in both cases (Note is is /resources/.... This is assuming say your directory structure is below:
MyProject
+src
+ressources
emitter.xml
Place the file alongside your source files, then you can use the getResourceAsStream() method in both cases. Don't forget to update the path (which should be the package name of your class, but with slashes instead of dots).
My question is: is there any better way to do this without having to
change my code if I want to export it or if I want to debug it?
Yes, use Maven. Maven will handle that and it hooks into Eclipse beautifully (NetBeans too!) What you do is place the resource in src/main/resources and then you can have Eclipse run the test goal of the Maven project or you can just run mvn test from the command line. Another advantage of using Maven here is that you can also have src/test/resources/emitter.xml which overrides the one in src/main with environment-specific test instructions and it won't affect your deployment.
InputStream i= getClass().getClassLoader().getResourceAsStream("ressources/emitter.xml");
or
InputStream i= getClass().getResourceAsStream("/ressources/emitter.xml");
(note the absolute positioning)
both work when the class is in the same jar, on the same class path.
In the jar the names must be case sensitive, but as the jar already works. Ensure that the ressources directory is on the class path too, or copied to the target directory.
As "ressources" is probably configured yourself (not named "resources" as in English), you probably need to add it to the build somehow.

Categories

Resources