Can not find file that is in resource folder - java - 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).

Related

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.

Relative resource paths in Java project in IntelliJ IDEA

I am trying to display an icon in my GUI by using a relative path, as in "display image from resources/image.png". I have tried a million different ways to express this, but nothing works. This makes me think it's a problem with my IntelliJ IDEA settings or project structure. I have set up the "resources" folder as a "resources folder". I don't know what else it expects me to do.
How can I load an icon from a file using a relative path in a Java project within IntelliJ IDEA?
My project structure:
src/main/java/ <-- set as "sources" in IntelliJ
src/main/java/ui/ <-- contains classes for my GUI
src/main/resources/ <-- set as "resources" in IntelliJ. Contains images.
Edit: Able to use relative path to confirm that file is found, not able to load it as icon.
String path = "src/main/resources/image.png";
System.out.println(new File(path).exists()); <-- true
I've encountered this issue many times and what worked for me was using InputStream
InputStream is = Main.class.getClassLoader().getResourceAsStream("name_of_file.png");
Using InputStream will allow you read from various file types. Now to load in the icon you can do
Icon icon = new ImageIcon(ImageIO.read(is));
Resources are on classpath, not on filesystem path - which is taken relative from running directory, which is project directory when you are running it from idea. Usually you will distribute your aplication as jar, and this it is better to load resources from classpath. In zour case - from root directory

Using relative path in a maven project

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.

Getting resources works from NetBeans Execution Context but not working when jar is executed from comand line

I have a code where i create Java Actions and try to associate Icons with them. One snapshot of code is
FileOpenCommand fileOpen = new FileOpenCommand(this);
fileOpen.putValue("ImageOnly", false);
fileOpen.putValue(Action.NAME, "Open");
fileOpen.putValue(Action.SMALL_ICON, new ImageIcon(getClass().getResource("../resources/File-Open-icon24x24.png")));
fileOpen.putValue(Action.SHORT_DESCRIPTION, "Opens the existing file.");
fileOpen.putValue("Group", "File");
fileOpen.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
this.commands.put("FileOpen", fileOpen);
The accent is on the line where I try to set the Action.SMALL_ICON property to the action. This works when executed in NetBeans environment either in debug or release mode. But when I've tried to execute jar file from the command line, it fails with exception.
Any idea? Anything to do with classpath? Resources folder is put as the package inside the main package.
Thanks in Advance!
I'm not entirely sure what exception is being thrown in your case, although assuming it is a NullPointerException, IOException, or IllegalArgumentException deriving from
fileOpen.putValue(Action.SMALL_ICON, new ImageIcon(getClass().getResource("../resources/File-Open-icon24x24.png")));
Your issue should be resolved simply by adding getClassLoader() between the getClass() and getResource(), like so:
fileOpen.putValue(Action.SMALL_ICON, new ImageIcon(getClass().getClassLoader().getResource("../resources/File-Open-icon24x24.png")));
Additionally, you must be exact in your filenames, specifically the extension. In this case, you are accessing File-Open-icon24x24.png, which will work perfectly fine regardless of whether the actual file is extended by png or PNG within Netbeans, but once exported the extension case matters.
Lastly, if neither of those changes resolve your problem, I would check your filepath, as there is most likely a logical error somewhere down the line.
When using embedded resources in Netbeans, you should have a resources folder containing additional folder or whatever data you need, which you seem to have, but this folder should be located inside the Netbeans project's src folder. getClass().getResource() returns the directory at the top of the package line, meaning if your class package is com.example.code, then the compiler will look for files/folder on the same level as com. Opening the Netbeans src folder you should see the initial com folder. Your resource folder should be placed directly next to that folder, as then it will be properly embedded in the jar file export.
In your code your path is ../resources/File-Open-icon24x24.png, which confuses me as to why you begin with ... I cannot see your folder structure so I cannot give a precise answer on this note, but you may be accessing the wrong location, although I feel like you are not as you said your project runs correctly within Netbeans. However, your resource files may not be correctly encoding into the jar file due to placement as mentioned. To test what your jar file actually contains, make a copy of it (for safety reasons) and change the file extension from jar to zip. You can then look through its contents in Windows Explorer, and see its directory structure. Another debugging trick for folder structures is to create a text file at the URL you are trying to access to see where it is placed.

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

Categories

Resources