Relative path's to images and sound in Java - java

Currently the project that I am making is game made with Jframe/Jpanel. I am using imports of images and sound through:
images:
ImageIcon a = new ImageIcon("C:/Users/Home/IdeaProjects/Game/src/DragonRoll/sprites/user_sprite_down.png");
player = a.getImage();
//sign
Sound:
String gongFile = ("C:/Users/Home/IdeaProjects/Game/src/DragonRoll/music/game_track.wav");
InputStream in = new FileInputStream(gongFile);
AudioStream audioStream = new AudioStream(in);
AudioPlayer.player.start(audioStream);
The images and the soundtrack from the example is seen to be imported from a direct path not a relative one meaning that it does not work on other computer or devices since they do not have the exact same path. Can someone recommend any solutions to this, please provide example code. I have tried just removing the path except the folder which contains the images and the image name itself but that did not work.
I am using Intellij and running as an executable java file.
Also the folder which contains all of the project goes like:
- Main project folder
- Branches into .idea, out and src
- src contains classes of the game and 2 folders called images and music

By convention source files in a Java project (everything that ends with .java) should be in a folder called src/main/java. Resources such as images, audio files, default config files, etc. are usually placed in a second source folder called src/main/resources. This way the compiled sources (i.e. the .class files) and the resource files will be on the classpath at run time of your application.
To load for example the src/main/resources/DragonRole/music/game_track.wav resource from your classpath you can simply do this:
InputStream gameTrackIn = MyClass.class.getResourceAsStream(
"/DragonRole/music/game_track.wav");
To load the src/main/resources/DragonRoll/sprites/user_sprite_down.png resource from your classpath you can simply do this:
ImageIcon userSpriteDownImg = new ImageIcon(MyClass.class.getResource(
"/DragonRoll/sprites/user_sprite_down.png"));
Your project structure should look like this:
Game (project root)
└ src/main
├ java (source root)
└ resources (resource root)

Basing on your comment responses, I propose you to place your resource files inside the jar.
After, Accessing to a resource file can be done in a such way : YourClass.class.getResource("sun.png") if the file is at the correct place.
Your main task now is placing the resource files to the convenient place and ensuring that you build allows to create the JAR with the expected files in the expected directory.
You don't seem to use Maven. It is not a prerequisite but it could easy your work to create the jar.
It's a common question. You should find some good examples about it.

Ended up using:
ImageIcon c = new ImageIcon("src/main/resources/sprites/new_background_panel.png");
Meaning it was looking from the source folder and not the whole computers path, thanks all others who helped out.

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.

Java relative path start from my src folder

I wanna use relative path start from my src folder to get file from resource folder.
File myFile = new File("/src/main/resources/filefolder/file.xml");
When I try this:
File myFile = new File("../src/main/resources/filefolder/file.xml");
Or this:
File myFile = new File("../../../../src/main/resources/filefolder/file.xml");
I get:
java.io.FileNotFoundException: /srv/../src/main/resources/filefolder/file.xml(No such file or directory)
My file structure:
-src
-main
-java
-com.my.site
-task
-MyClass.java
-resources
I see you are asking about the relative path but seems like you want to just read the file from resources, I believe the most common way to read resources is by using the class loader, example:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("filefolder/file.xml").getFile());
your path is correct, just add dot before src, to indicate that you are searching relative path to project root directory, in other case you'll search by absolute path
File myFile = new File("./src/resources/filefolder/file.xml");
if doesn't work - try this:
File myFile = new File("src/resources/filefolder/file.xml");
anyway you can run this to check what is your root dir:
public static void main(String[] args) {
System.out.println(new File("").getAbsolutePath());
}
Just a little explanation... What you want to do is get a resource from the resource folder, that's a quite typical task.
What you do have to realize is, that the whole /src/main/etc. structure is there to structure your source code, in other words, the .java files (and resource files). In your compiled program, this structure will not longer exist in the same way, so relying on a src directory is a very, very bad idea.
This structure is there for maven:
src/main -> Everything that should be part of the "program" all the time
src/test -> Everything that should only be part of the "program" when running automated tests
src/main/java -> .java files that need to be there always
src/main/resources -> Resources (images, templates, etc.) that need to be there always
src/test/java -> .java files that are only needed during automated tests (for example, the automated tests themselves)
src/test/resources -> Resources that are only used in automated tests, for example, files to compare results against, etc.
Where does this lead us? It leads to the simple fact, that, in the end, the whole src/main and src/test will simply not exist and indeed, java and resources will be added together (you can check this by looking at a .jar file - it can be opened with any Zip-Program). This is, why #LazerBanana is entirely correct: You do not try to navigate directories, you ask for resources and the resources are inside your classpath - and it does not matter, if they are in the resources or java folder (because that's just to keep your source code structured). In your class path, both folders come together.

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

How to give path to a resource in java swing

To give path to a resource eg:- image, in javafx, we can do as :-
ImageView imgView_btnEndCall = new ImageView(new Image("/clientgui/image/callend.png"));
But to give path to a resource in swing, the following code works
FileInputStream fis = new FileInputStream("src/soundtest/sound/sound.wav");
The difference I found is necessity to put 'src' in swing. And when I run the jar file from dist folder, swing program doesnt work but javafx program works. Problem is because the jarfile compress the project including all the packages and files. When javafx program tries to access some resource, it is able to access, callend.png file inside image folder inside clientgui folder. But swing application cant access as we have given 'src' folder in the code. How to solve the problem. How to include the resource directory in swing so that the jar file can access the resource.
Don't use FileInputStream, use the ClassLoader, e.g.
getClass().getResourceAsStream("sound/sound.wav");
getResouceAsStream() javadoc
This will load the file from the directory structure contained in your jar. The src folders won't exist anymore when the jar is created, they will be an embedded resource (thanks #AndrewThompson for the buzzword).
Read more in this question: Embedding resources (images, sound bits, etc) into a Java project then use those resources
Well thanks to durron597, my code worked. As I mentioned in my question, the problem was jar file doesnt have src folder and can't access the resource as I mentioned in my question. Taking the resource using ClassLoader solved the problem. Here is my final code
AudioStream audio = new AudioStream(getClass().getResourceAsStream("sound/sound.wav"));
AudioPlayer.player.start(audio);
Here, package name is soundtest and inside that package, there is another folder called sound which has a wav file sound.wav
soundtest
|-sound
|-sound.wav

How to access a Image file in a Eclipse Project Folder

I have a single image file in a folder in my Eclipse project that stores a image file (logo.jpg). However I don't know how to access it in my main program.
I had tried the following
private static URL logoPath
public class MainApplication
{
public void createGui()
{
logoPath.getClass().getResource("/Resources/images/logo.jpg");
////
}
/////
}
Problem is I keep getting a null pointer exception so obviously that path is done wrong or else the logoPath.getClass() is tripping it up.
Any ideas?
U can use this way
I have following package structure
src/test (package test contain Java files)
src/images (folder images contain images)
I am going to get image from
src/images/login.png at src/test/*.java
JLabel label = new JLabel(new ImageIcon(getClass().getResource("/images/login.png")));
You need to place your resources in a java source directory for them to be visible. You have two options:
Move your "resources" folder under your existing "src" folder.
Create a new source folder just for resources. You can do that in Java Build Path page of project properties.
Several things to watch out for...
Pay attention to your capitalization. Java resource lookup is case sensitive.
The path that you would use will be relative to the source folder (not project root). For instance, if you make your resources folder a source folder, your path will need to be "images/...". If you want to preserve resources folder in the lookup path, you will need to create an extra folder level in your project to serve as the source root for resources.
I am not certain whether it is an actual problem, but resources paths should not start with a leading slash. They aren't really paths in a traditional sense. Think of them as package-qualified class names, but with '/' instead of '.' as the separator.
I am doing that the same way
String filename = "logo.jpg";
Main.getClass().getClassLoader().getResource(filename);
And the file structure looks like this
/src/main/java/com/hauke/Main.java
/resource/logo.jpg
My problem was before that I named the direcotry "resources" and it should be "resource"

Categories

Resources