I have a project structure like this:
src
|-main
|-java
|-com.abc.xyz
|-Login.java
I have to add a resource file to this and read the resource with
InputStream is = getClass().getResourceAsStream("launchers.properties");
This is giving null.
In Intellij I am not able to add a new package under src/main for resources folder so
that the project structure looks like this. How can I load the launchers.properties resource file into the project?
src
|-main
|-java
|-com.abc.xyz
|-Login.java
|-resources
|-com.abc.xyz
|-Login
|-launcher.properties
I tried the solution suggested by #maba but still not working
The launcher.properties should not be under a folder called Login. It should be placed directly in the src/main/resources/com/abc/xyz folder.
It is really as simple as I said but if the resources folder is not marked as a sources folder then this may be the problem.
This is the initial class and setup:
Now create the resources folder:
This newly created folder should be automatically marked as a sources folder and if it is blue color marked then it is. Otherwise you'll have to mark it manually:
Now you'll be able to add packages to it:
And now you can add the file to it:
And rerunning the application will not give you any null value back:
And the package view will surely show the launchers.properties file as well:
As #maba pointed out, your properties file should be in the same package as your class for your code to work.
So, you should have two files:
src/main/java/com/abc/xyz/Login.java
src/main/resources/com/abc/xyz/launcher.properties
If IntelliJ is showing the resource or not is beside the question. What you need to do is check if the results are included in your target artefact.
Do a build all in IntelliJ, open up the resulting WAR/JAR/EAR with your favorite ZIP viewer and browse into the "com/abc/xyz" folder. You should see both files there.
If they are, you are doing something wrong in your code. Check for typos, especially dots and spaces at the end or beginning (e.g. "launcher.properties[space]"), copy/paste the file name to make sure
If they are not there, your IntelliJ setup is wrong. Resources do not get included in your target build. Check online for tutorials how to do this with IntelliJ idea.
Follow these two steps
1) Create a directory
Right Click ==> New ==> Directory
2) Mark Directory as Resources Root
Right Click on the Direcory ==> Mark Directory as ==> Resources Root
No..... the structure is wrong.... you should not create the same package under resources, that is ugly and not proper: resources is for resources, and should not contain source packages.
When using ClassLoader.getResources(asStream)(path) method, the method just starts searching from the root of the classpath and the path name cannot start with / as leading characters. What you have to do, is to mark the resources as resources folder in IntelliJ. Then the files under resources will be listed under classpath and you can easily use them like you have done.
(I see in previous answers this option is not available yet in 2013, you only have mark as source folder, just like in Eclipse till now we have "add source folder", but now in 2018 it is available in Intellij: you can mark a folder as source, resources, test source, test resources, and all of them will be add to the root of classpath. )
I had the same problem and noticed that the resource file, for example: my.properties is not copied to the corresponding module folder in the target directory after build occurres. In order to solve that, I had to instruct Maven to copy the resources from the module directory to the target directory during the build process. In the .pom file I added <resource> element like that:
<project ...>
...
<build>
...
<resource>
<directory>src/main/java/com/abc/xyz</directory>
<targetPath>com/abc/xyz</targetPath>
</resource>
</build>
...
</project>
Note that the <directory> element is relative to the location of the .pom file , i.e. the root directory of the project, and the <targetPath> element indicates the package name separated by slashes.
from menu Run/edit configuration
in VM option you should add
-Dspring.config.location=path-file
I've tried it in IntelliJ, and it works!
Only solution worked for me:
File -> Project Structure -> Modules -> Dependencies Tab -> + Sign -> JARs or directories -> select resources directory -> Classes
Related
I have a Java Project in NetBeans 7.0.
I want to add some image to some label dynamically. The image will differ depending on the state of the program.
I put one such image, 'filling.jpg', in the 'resources' folder of my project.
I want to reach this file correctly (not by absolute or relative path, because that will cause problems when I build the jar file).
So I found this method:
ImageIcon fillingIcon = new ImageIcon(getClass().getClassLoader().getResource("filling.jpg"));
labelFontFilling.setIcon(fillingIcon);
It keeps give me java.lang.NullPointerException.
But I am sure that there is that image, because I can assign the image to the label from the NetBeans Properties menu for that label (but I don't want this, I want to add the image by Java code).
What am I doing wrong, and how can I get that image correctly?
This was a pain, using netBeans IDE 7.2.
You need to remember that Netbeans cleans up the Build folder whenever you rebuild, so
Add a resource folder to the src folder:
(project)
src
project package folder (contains .java files)
resources (whatever name you want)
images (optional subfolders)
After the clean/build this structure is propogated into the Build folder:
(project)
build
classes
project package folder (contains generated .class files)
resources (your resources)
images (your optional subfolders)
To access the resources:
dlabel = new JLabel(new ImageIcon(getClass().getClassLoader().getResource("resources/images/logo.png")));
and:
if (common.readFile(getClass().getResourceAsStream("/resources/allwise.ini"), buf).equals("OK")) {
worked for me. Note that in one case there is a leading "/" and in the other there isn't.
So the root of the path to the resources is the "classes" folder within the build folder.
Double click on the executable jar file in the dist folder. The path to the resources still works.
I have a slightly different approach that might be useful/more beneficial to some.
Under your main project folder, create a resource folder. Your folder structure should look something like this.
Project Folder
build
dist
lib
nbproject
resources
src
Go to the properties of your project. You can do this by right clicking on your project in the Projects tab window and selecting Properties in the drop down menu.
Under categories on the left side, select Sources.
In Source Package Folders on the right side, add your resource folder using the Add Folder button. Once you click OK, you should see a Resources folder under your project.
You should now be able to pull resources using this line or similar approach:
MyClass.class.getResource("/main.jpg");
If you were to create a package called Images under the resources folder, you can retrieve the resource like this:
MyClass.class.getResource("/Images/main.jpg");
Thanks, Valter Henrique, with your tip i managed to realise, that i simply entered incorrect path to this image.
In one of my tries i use
String pathToImageSortBy = "resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
But correct way was use name of my project in path to resource
String pathToImageSortBy = "nameOfProject/resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
For me it worked like I had images in icons folder under src and I wrote below code.
new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));
I currently have two projects:
api-test
...
/config/config.json
...
and
ui-test
...
/config/config.json
...
In eclipse, I am adding api-test in the build path of ui-test, so that api-test is the dependency of ui-test.
However the build failed, because api-test is looking for the config.json located in api-test/config/config.json by calling:
System.getProperty("user.dir") + "/config/config.json"
which does not exist in ui-test project.
the two config.json include different contents - what would be the best solution to let each project refer to their own config.json while ui-test is referring to api-test project?
Put the files into the projects' src/main/resources directories as suggested by Maven's Standard Directory Layout. You can use relative paths to access these resources then.
See How to get file resource from Maven src/test/resources/ folder in JUnit test? For instance:
Test file existence
#Test
public void testStreamToString() {
assertNotNull("Test file missing", getClass().getResource("/sample.txt"));
...
}
Package
|
|------src/main/java
|------resources
|---- config.properties
In pom.xml, I have set resoucres directory as follows
<resources>
<resource>
<directory>resources</directory>
</resource>
</resources>
I'm able to get the absolute path of the file. But When I try to read or check whether it is a file or directory, it is return false.
sample.java
File configFile = new File("config.properties");
System.out.println("PATH="+newFile.getAbsolutePath());
System.out.println("IsFile="+newFile.isFile());
System.out.println("CanRead="+configFile.canRead());
Output
PATH=D:\JCB\MyWorkSpace_LunaJEE\MessageProcessor\config.properties
IsFile=false
CanRead=false
Any help will be appreciated.
In pom.xml, I have set resoucres directory as follows
That defines the directory where resources will be stored as part of the Maven build structure - so it specifies where Maven should look for resource files to include in your program. It does not define where files can be found when running your application. It is not really a good idea to change from the Maven conventions, keep it as src/main/resources if you can. If you use external tooling on top of Maven, you may get conflicts otherwise.
What is the important part is what happens with the files when the application is built by Maven when you do for example a mvn clean install.
whatever is in src/main/java is compiled and the classes are put in the target directory, in their proper package structure. The files and directories in the src/main/resources folder are copied to that same target directory. The resources are thus made part of your Java program and are available on the classpath; if you would let Maven build your application into an executable jar at this point for example, the resources will be packaged together with the classes inside that jar.
To properly load the resource files packaged with your application, you should use Java's classloader system. This question's answer demonstrates that in detail. To change your current test code, you would rather do something like this:
InputStream is = getClass().getClassLoader().getResourceAsStream("config.properties");
if(is != null){
// yep, the file exists on the classpath! Now load it with the InputStream
}
The file is not in D:\JCB\MyWorkSpace_LunaJEE\MessageProcessor\config.properties, but in the resources folder there, so it does not exist and thus is neither file nor directory. I would suggest putting it in /src/main/resources and then accessing it via getResourceAsStream( name );
All, Forgive me I am still learning the Java development right row.
Say we have the structure of web project like below.
The src and config is under the Java Resources folder of web project.
src
...
|- a.b.c.package
|-test.java
...
config
|-1.xml
|-2.xml
...
configfolder
|-1.properties
|-2.properties
testfolder
|-test.properties
I want to know if I use the dom4j. How to read the xml file(1.xml) within the test.java. Thanks.
My Experiment
In the test.java. I found I can succeed to use the class.getClassLoader().getResourceAsStream("test.properties") to load test.properties in any folders or sub folder of src.
Does it mean getResourceAsStream can search the specified file in any of the folders of project recursively? I just can't understand it how it works. Thanks.
getResourceAsStream() method searches for resources with classpath as root. I suppose in your case 'testfolder' is source folder. I you would have your 1.properties in 'testfolder/mypath/1.properties' then you need to specify getResourceAsStream("mypath/1.properties")
I have a Java Project in NetBeans 7.0.
I want to add some image to some label dynamically. The image will differ depending on the state of the program.
I put one such image, 'filling.jpg', in the 'resources' folder of my project.
I want to reach this file correctly (not by absolute or relative path, because that will cause problems when I build the jar file).
So I found this method:
ImageIcon fillingIcon = new ImageIcon(getClass().getClassLoader().getResource("filling.jpg"));
labelFontFilling.setIcon(fillingIcon);
It keeps give me java.lang.NullPointerException.
But I am sure that there is that image, because I can assign the image to the label from the NetBeans Properties menu for that label (but I don't want this, I want to add the image by Java code).
What am I doing wrong, and how can I get that image correctly?
This was a pain, using netBeans IDE 7.2.
You need to remember that Netbeans cleans up the Build folder whenever you rebuild, so
Add a resource folder to the src folder:
(project)
src
project package folder (contains .java files)
resources (whatever name you want)
images (optional subfolders)
After the clean/build this structure is propogated into the Build folder:
(project)
build
classes
project package folder (contains generated .class files)
resources (your resources)
images (your optional subfolders)
To access the resources:
dlabel = new JLabel(new ImageIcon(getClass().getClassLoader().getResource("resources/images/logo.png")));
and:
if (common.readFile(getClass().getResourceAsStream("/resources/allwise.ini"), buf).equals("OK")) {
worked for me. Note that in one case there is a leading "/" and in the other there isn't.
So the root of the path to the resources is the "classes" folder within the build folder.
Double click on the executable jar file in the dist folder. The path to the resources still works.
I have a slightly different approach that might be useful/more beneficial to some.
Under your main project folder, create a resource folder. Your folder structure should look something like this.
Project Folder
build
dist
lib
nbproject
resources
src
Go to the properties of your project. You can do this by right clicking on your project in the Projects tab window and selecting Properties in the drop down menu.
Under categories on the left side, select Sources.
In Source Package Folders on the right side, add your resource folder using the Add Folder button. Once you click OK, you should see a Resources folder under your project.
You should now be able to pull resources using this line or similar approach:
MyClass.class.getResource("/main.jpg");
If you were to create a package called Images under the resources folder, you can retrieve the resource like this:
MyClass.class.getResource("/Images/main.jpg");
Thanks, Valter Henrique, with your tip i managed to realise, that i simply entered incorrect path to this image.
In one of my tries i use
String pathToImageSortBy = "resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
But correct way was use name of my project in path to resource
String pathToImageSortBy = "nameOfProject/resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
For me it worked like I had images in icons folder under src and I wrote below code.
new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));