Intellij Scala/Java add resource folder - java

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.

Related

Java: I do not Understand the Relative Paths

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

InputStream gives IllegalArgumentException for just the jar file [duplicate]

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.

Unknown Path FXML document

We're writing an Java application using JavaFX. At this time we have 3 different forms:
Login
Game window
Registration
For our next iteration, we want to implement the Registration form, but we get the IOException error Unknown Path
It's about this piece of code:
FXMLLoader registrationLoader = new FXMLLoader();
try{
mainroot = (Parent)registrationLoader.load(this.getClass().getResource("FXMLRegistration.fxml").openStream());
Stage registrationStage = new Stage();
Scene scene = new Scene(mainroot);
registrationStage.setScene(scene);
registrationStage.setTitle("Register your account");
registrationStage.show();
} catch(IOException ex)
{
System.out.print(ex.getMessage());
}
The above code is working when I change FXMLRegistration.fxml to FXMLDocument.fxml or FXMLLoader.fxml.
When I change
mainroot = (Parent)registrationLoader.load(this.getClass().getResource("FXMLRegistration.fxml").openStream());
to
mainroot = (Parent)registrationLoader.load(Paths.get("src/hackattackfx/FXMLRegistration.fxml").toUri().toURL());
source
I get the absolute path in the debugger output, which is correct when I use it with the file command in terminal.
I hope someone could help us with this error.
Thanks in advance!
EDIT
I Changed some code to the following:
FXMLLoader registrationLoader = new FXMLLoader(getClass().getResource("/FXMLRegistration.fxml"));
mainroot = (Parent)registrationLoader.load();
but this will return an IllegalStateException: Location is not set.
When I remove / before /FXMLRegistration.fxml, I get to my catch block printing the full path of the file:
file:/Users/juleskreutzer/Documents/github/PTS3/HackAttackFX/dist/run1793658053/HackAttackFX.jar!/hackattackfx/FXMLRegistration.fxml
Also changing the path to src/hackattackfx/FXMLRegistration.fxml will give the IllegalStateException: Location not set.
Project Structure
We use different packages in our application. all these packages are within the default package: hackattackfx
The packages in the default package are:
Default Package
Exceptions
Interfaces
enums
Resources
Templates
JSON Package
My FXML documents are located in the default package (hackattackfx). If it's not 100% clear how I arranged my files, please take a look at my Github repo
So, I got all curious to find out the root cause, I cloned the repo and found that the actual issue was the following error and the one that was posted by the OP in the question
Caused by: java.lang.NullPointerException
at hackattackfx.FXMLRegistrationController.initialize(FXMLRegistrationController.java:67)
Which means that in the controller pane was null.
This was because the fxml was missing a declaration of fx:id .
Add fx:id="pane" to the AnchorPane declaration of FXMLRegistration.fxml and things should just work fine.
You need to start your Path with /
this is working for me:
final String fxmlPath = "/fxml/Main.fxml";
final FXMLLoader loader = new FXMLLoader(this.getClass().getResource(fxmlPath));
Main.fxml is located in the resource folder (for me: /src/main/resources/fxml/)

Error reading image from scala playn

I researched and looked into the PlayN game framework and I liked it a lot. I program in Scala and actually don't know Java but it's not usually a problem since they work together great.
I've set up a basic project in eclipse and imported all the libraries and dependencies. I even translated over the base maven project code. Here's the two files:
Zeitgeist.scala
package iris.zeit.core
import playn.core.PlayN._
import playn.core.Game
import playn.core.Image
import playn.core.ImageLayer
class Zeitgeist extends Game {
override def init (){
var bgImage: Image = assets().getImage("images/bg.png")
var bgLayer: ImageLayer = graphics().createImageLayer(bgImage)
graphics().rootLayer().add(bgLayer)
}
override def paint (alpha: Float){
//painting stuffs
}
override def update(delta: Float){
}
override def updateRate(): Int = {
25
}
}
Main.scala
package iris.zeit.desktop
import playn.core.PlayN
import playn.java.JavaPlatform
import iris.zeit.core.Zeitgeist
object Main {
def main(args: Array[String]){
var platform: JavaPlatform = JavaPlatform.register()
platform.assets().setPathPrefix("resources")
PlayN.run(new Zeitgeist())
}
}
The cool thing is it works! A window comes up perfectly. The only problem is I can't seem to load images. With the above line, "assets().getImage("images/bg.png")" it pops out
Could not load image: resources/images/bg.png [error=java.io.FileNotFoundException: resources/images/bg.png]
I've played around with the location of my resources file to no avail. I was even able to find bg.png myself with java.io.File. Am I doing something wrong? Is there something I'm forgetting?
Looking at the code of JavaAssetsManager, it looks like it is trying to load a resource and not a file. So you should check that your images are actually in the classpath and at the path you give ("resources/images/bp.png")
Alternatively, you can use getRemoteImage and pass a File URL. As you succeeded in using a java.io.File, you can just get the URL with method toUri of File (toUrl is deprecated).
This almost certainly doesn't work because you're doing this:
platform.assets().setPathPrefix("resources")
That means you're saying your source folder looks like this:
src/main/resources/resources/images/bg.png
src/main/resources/resources/images/pea.png
src/main/resources/resources/images
I imagine it actually looks like one of these:
src/main/resources/assets/images/bg.png <-- 'assets' the default prefix
src/main/resources/assets/images/pea.png
src/main/resources/assets/images
or:
src/main/resources/images/bg.png <-- You have failed to put a subfolder prefix in
src/main/resources/images/pea.png
src/main/resources/images
You can either do this, if you have no prefix:
plat.assets().setPathPrefix("")
Or just put your files in the assets sub-folder inside the resources folder.
It's worth noting that the current implementation calls:
getClass().getClassLoader().getResource(...)
Not:
getClass().getResource(...)
The difference is covered elsewhere, but the tldr is that plat.assets.getImage("images/pea.png") will work, but plat.assets.getImage("/images/pea.png") will not.

How do I load a LWUIT theme file into my Java project?

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.

Categories