I am relatively new to Java, so bear with me.
I am completing a tutorial on LWUIT, and just want to load a simple theme, created using the editor. Here is the code in question:
try
{
Container container = c.getContainer();
container.setVisible(true);
Display.init(container);
Display.getInstance().setPureTouch(true);
//Resources r = Resources.open(getClass().getResourceAsStream("/res/Theme.res"));
Resources r = Resources.open("/res/Theme.res");
UIManager.getInstance().setThemeProps(r.getTheme("Simple"));
}
When I use the first (commented out) statement, I get
*** Signal: alarm { "name":"XletException", "domain":"ams", "appId":"com.thomasdge.xlet.hellojamaica.HelloJamaica", "msg":"XletAction['initXlet'] resulted in exception com.aicas.xlet.manager.AMSError: running xlet code caused java exception: initXlet() resulted in exception: java.lang.NullPointerException: <null>.read()I", "data":{ } }
When I use the other, I get
java.io.IOException: /res/Theme.res not found
I have my Theme.res file in /res/Theme. I have also tried it directly in the root, as well as /src. Same results for each.
Any ideas?
If you put the res file in that folder, you will need to go down one level. I recommend you to put the res in the src folder. So, /src/Theme.res. In the code you will only need to write Resources r = Resources.open("/Theme.res");
If resource file placed in res folder, you need to add res folder in project properties. Also you mentioned, the problem even in /src folder, I feel you didn't change the path. Just use Resources.open("/Theme.res") when you use /src folder. Also check the theme name. This should work.
Related
I've got following maven project structure as also seen in here (ProjectStructure) :
-maws20.algorithm
|-src/main/resources
|-images
|-menuBanner
|-linearSearchMenuBannerUnsorted.png
|-src/main/java
|-linearSearch.menu
|-LinearSearchMenuBanner.java
I am trying to load that .png image inside of the LinearSearchMenuBanner.java-File with the following Line:
#Override
public Image loadBackgroundImage() {
return new Image(LinearSearchMenuBanner.class.
getResource("/images/menuBanner/linearSearchMenuBannerUnsorted.png").toString());
}
Is this not the correct relative path? Because I get the following error:
...
Caused by: java.lang.NullPointerException: Cannot invoke "java.net.URL.toString()" because the return value of "java.lang.Class.getResource(String)" is null
at linearSearch.menu.LinearSearchMenuBanner.loadBackgroundImage(LinearSearchMenuBanner.java:20)
...
(Line 20 is the line shown above)
I thought I understood the relative paths in Java. ^^'
Thank you for any help.
Remove the first back slash /, which actually means absolute path not the relative path.
Try this:
#Override
public Image loadBackgroundImage() {
File resource = new ClassPathResource("images/menuBanner/linearSearchMenuBannerUnsorted.png").getFile();
return new Image(new String(Files.readAllBytes(resource.toPath()));
}
To know more, you can visit this link: spring-classpath-file-access
Thanks for all your help. I don't know what went wrong, but when i create a completly new Workspace after that create all files new and copy the source code to the new files. Then it works fine.
I dont know why...
But thank you very much :)
I guess this is related to your packaging. The image needs to be on the servers file system, the JAR resources will not work!
ClassPathResource
Supports resolution as java.io.File if the class path resource resides in the file system, but not for resources in a JAR. Always supports resolution as URL.
You are in package search.menu and you need to access the file resource in images/menuBanner So you need to load a resource:
new ClassPathResource(“../../images/menuBanner/linearSearchMenuBannerUnsorted.png
“, LinearSearchMenuBanner
.class).getFile();
Hava a look into other options here:
https://www.baeldung.com/spring-classpath-file-access
The line persistenceProperties.load(is); is throwing a nullpointerexception in the following method. How can I resolve this error?
public void setUpPersistence(){
final Properties persistenceProperties = new Properties();
InputStream is = null;
try {
is = getClass().getClassLoader().getResourceAsStream("src/test/samples/persistence.properties");
persistenceProperties.load(is);
}catch (IOException ignored) {}
finally {
if (is != null) {try {is.close();} catch (IOException ignored) {}}
}
entityManagerFactory = Persistence.createEntityManagerFactory(
"persistence.xml", persistenceProperties);
}
I have tried to experiment with this by moving the class that contains the method to various other locations within the application structure, and also by changing the line of code preceding the error in the following ways:
is = getClass().getClassLoader().getResourceAsStream("persistence.properties");
is = getClass().getClassLoader().getResourceAsStream("/persistence.properties");
is = getClass().getClassLoader().getResourceAsStream("/src/test/samples/persistence.properties");
is = getClass().getClassLoader().getResourceAsStream("other/paths/after/moving/persistence.properties");
But the error is still thrown every time the method is called.
Here is a printscreen of the directory structure of the eclipse project. The class containing the method is called TestFunctions.java, and the location of persistence.properties is shown:
**EDIT: **
As per feedback below, I changed the method to:
public void setUpPersistence(){
final Properties persistenceProperties = new Properties();
InputStream is = null;
try {
is = getClass().getClassLoader().getResourceAsStream("persistence.properties");
persistenceProperties.load(is);
}catch (IOException i) {i.printStackTrace();}
finally {
if (is != null) {try {is.close();} catch (IOException ignored) {}}
}
entityManagerFactory = Persistence.createEntityManagerFactory(
"persistence.xml", persistenceProperties);
}
I also moved mainTest.TestFunctions.java to src/test/java. Together, these all cause the following new stack trace:
Exception in thread "main" java.lang.NoClassDefFoundError: maintest/TestFunctions
at maintest.Main.main(Main.java:7)
Caused by: java.lang.ClassNotFoundException: maintest.TestFunctions
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
... 1 more
Short answer:
Move persistence.properties to src/main/resources, have both Main.java and TestFunctions.java in src/main/java, and use
getClass().getClassLoader().getResourceAsStream("persistence.properties");
to load the properties file.
Long answer with an explanation:
As others have hinted at - in a Maven project structure, you (typically) have two directory trees: /src/main and /src/test. The general intent is that any "real" code, resources, etc should go in /src/main, and items that are test-only should go in /src/test. When compiled and run, items in the test tree generally have access to items in the main tree, since they're intended to test the stuff in main; items in the main tree, however, do not typically have access to items in the test tree, since it's generally a bad idea to have your "production" code depending on test stuff. So, since Main.java depends on TestFunctions.java, and TestFunctions.java depends on persistence.properties, if Main is in src/main then both TestFunctions and persistence.properties need to be as well.
Two things:
First, try a path of test/samples/... or /test/samples/...
Secondly, and much more importantly, don't ever, ever, ever write this:
try {
// some stuff
} catch (IOException ignored) {}
All this says is: do some stuff, and if it goes wrong, then fail silently. That is never the right thing to do: if there's a problem, you want to know about it, rather than madly rushing on as if nothing had happened. Either do some sensible processing in your catch block, or else don't have the try/catch and add a throws IOException to your method signature so it can propagate upwards.
But at the moment, you're just sweeping things under the carpet.
ClassLoader.getResourceAsStream() loads resources as it does for loading classes. It thus loads them from the runtime classpath. Not from the source directories in your project.
Your class Main is in the package maintest, and its name is thus maintest.Main. I know that without even seeing the code because Main.java is under a directory named maintest, which is at directly under a source directory.
The persistence.properties file is directly under a source directory (src/test/resources). At runtime, it's thus at the root of the classpath, in the default package. Its name is thus persistence.properties, and not src/test/samples/peristence.properties. So the code should be
getClass().getClassLoader().getResourceAsStream("persistence.properties");
Nothing will ever be loadable from the samples directory, since thisdirectory is not under any source directory, and is thus not compiled by Eclipse, and is thus not available to the ClassLoader.
I will try to make it more Simple for this Question!
Here your main class is in src/main/java as you mentioned, so you should create another source for storing your properties file saying src/main/resources which you had already done and just store your properties file in this source, so in Run time it will directly refer this path and access the file,
You can add this piece of code as well to access the properties file
is = ClassLoader.getSystemResourceAsStream("your_properties_file");
and you can use load(is) accordingly.
To Conclude
If your main class is in src/main/java then you should keep your properties file in src/main/resources and use the respective snippet to load this.
OR
If your main class is in src/test/java then you should keep your properties file in src/test/resources and use the respective snippet to load this.
Your IDE works with two different scopes:
production scope: src/main/java + src/main/resources folders and
test scope: src/test/java + src/test/resources
Seems you are trying to execute you program from production scope, while persistence.properties file is placed into test scope.
How to fix:
Place your test into src/test/java or
Move persistence.properties into src/main/resources
InputStream is = this.getClass().getResourceAsStream("/package_name/property file name")
PropertyFileOject.load(is)
In my case error was due to maven was not treating my config folder inside src/main/java as source folder.
Recreated config package in src/main/java ..Copied files to it and re-compiled using maven. Files were there in target directory and hence in war. Error resolved.
I recently had the same problem and came upon the solution that I had to put my resources in a path the same way organized as where was getClass().getResourceAsStream(name) situated. And I still had a problem after doing that. Later on, I discovered that creating a package org.smth.smth only had created a folder named like that "org.smth.smth" and not a folder org with a folder smth and a folder inside smth... So creating the same path structure solved my problem. Hope this explanation is understandable enough.
My project-structure:
-Project
--res
---test.jpg
---bla.xml
--src
---Main.scala
Now I want to load bla.xml in my Main.scala
object Main
{
val test = getClass.getResource("res/bla.xml")
}
Throws an IOException right into my face. Now how can I add the res-folder to the projects-searchpath?
I've already marked it as "resource folder".
If I place bla.xml at the root and load it with "bla.xml" everything is just fine, so I'm wondering how to do this in Intellij.
edit: Sascha Kolberg had it right:
Just use val test = getClass.getResource("/bla.xml") if you've added res as an resourcefolder.
My comment as answer:
afaik, all contents or resource folders are placed in the class path root. So just try
val test = getClass.getResource("/bla.xml")
Try val test = getClass.getResource("[full_path_to_bla.xml]"). If this works, slightly adjust, then you will figure out the correct relative path.
Please update us the correct one when you found it.
I am trying to understand how to use JPL. For this purpose I copied one of it's tests from the doc section (swipl\doc\packages\examples\jpl\java\Time) to eclipse and tried to run it.
If I double click the batch file, all runs well. If I run the Time class using eclipse I get
Exception in thread "main" jpl.PrologException: PrologException: error(existence_error(source_sink, 'time.pl'), _0)
I created a simple java project. Copied Time.java and time.pl to the root.
Also I created the needed Path variables and connected the jpl.jar to the project.
JPL.init() works. I fail on the if statement of this part:
static void test_0() {
Query query = new Query("consult('time.pl')");
if (!query.hasSolution()) {
The path to the prolog file should have the suffix of src/
Query query = new Query("consult('src/time.pl')");
I have added an image for my button,but when I run that frame this exception will be thrown .why?please help me.
init:
deps-jar:
compile-single:
run-single:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:138)
at ClientGUI.IdAndPasswordFrame.initComponents(IdAndPasswordFrame.java:91)
at ClientGUI.IdAndPasswordFrame.<init>(IdAndPasswordFrame.java:22)
at ClientGUI.IdAndPasswordFrame$4.run(IdAndPasswordFrame.java:200)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
BUILD SUCCESSFUL (total time: 1 second)
line 138:
public ImageIcon (URL location) {
this(location, location.toExternalForm());
}
line91:
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/yahoo_1.gif"))); // NOI18N
I use this poor checking (Peter Lang recommended)which is:System.out.println(getClass().getResource("/Images/yahoo_1.gif")); and it returns null,why? please help me.
This means, that getClass().getResource("/Images/yahoo_1.gif") returns null.
JavaDoc states that this happens if
the resource could not be found or the invoker doesn't have adequate privileges to get the resource.
Check if getResource really returns null:
System.out.println(getClass().getResource("/Images/yahoo_1.gif"));
Make sure that your path is correct and that it is in your classpath.
EDIT:
I just tried it with NetBeans. I created the following structure
Source Packages
Images
yahoo_1.gif
and your code worked fine. Is this your structure?
Try to right-click on your application and select Clean and Build.
In order to fix this, the images need to be copied in the bin directory - not in src directory.
Otherwise you will get null all the time on getClass().getResource("image.png").
The path is not null and you can set it as the above - only if you copy the images that you need inside the binary directory, where .class files for your project are located.
This fixed the problem. Let me know if I helped in this.
Ioana
I had the same problem. What worked for me was:
Look into the jar file or in the bin folder(the one with .class files) and see the path of image.
List item
It looks like getClass().getResource("/Images/yahoo_1.gif") returns null i.e. the .gif cannot be found on your classpath. (Images versus images maybe?)
The URL being passed in is null from this line:
getClass().getResource("/Images/yahoo_1.gif")
From the JDK documentation:
[getResource(..) returns] A URL object for reading the resource,
or null if the resource could not be
found or the invoker doesn't have
adequate privileges to get the
resource
Maybe you meant ("Images/yahoo_1.gif") - i.e. relative path not absolute?
private class HandlerClass implements ActionListener{
public void actionperformed(ActionEvent event){
JOptionPane.showMessageDialog(null, String.format("%s", event.getActionCommand()));
}
}
After reviewing some things when trying to add an image I was presented with the same problem that usually occurs in project with maven.
I found a solution that uses the full path to be able to access the image. Also, create a function that returns an icon with the image and automatically scaled according to the dimensions that are sent to it.
Path -> directory where the image is located, width -> width of the icon, heigth-> height of the icon I hope it serves you, this is my first contribution in the community
public Icon getIcon(String ruta, int width, int heigth) {
Image image = (new ImageIcon(ruta)).getImage().getScaledInstance(width, heigth, 0);
Icon mIcono = new javax.swing.ImageIcon(image);
return mIcono;
}