How to give path to a resource in java swing - java

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

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.

Spring does not find file in resources

i have following line
File file = ResourceUtils.getFile("classpath:calculation.csv");
and i also tried
File file = ResourceUtils.getFile("classpath:/calculation.csv");
but both will throw an error
java.io.FileNotFoundException: class path resource [calculation.csv] cannot be resolved to absolute file path because it does not exist
but i do have calculation.csv in by resources folder..
why is this?
I need to read file from resources folder, and it should also work in server enviroment
EDIT:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("calculation.csv").getFile());
works just as fine, so not at all..
EDIT2:
tried with folder.. i have both calculation.csv and csv/calculation.csv in my resources folder now..
none of the above work, with /csv/ added.
what kind of path does this thing want?!
EDIT3:
aaand
File file = new ClassPathResource("calculation.csv").getFile();
is also no go, what even is this..
Loading file (as FILE) wont work. You must use it as resource. Files inside JAR will not work as file anyway. This is also what your "check" code shows.
classLoader.getResource("calculation.csv") works, because you are using classloader to get resource, not filesystem to get file (which is what File api does). It could work, if you would deal with non packed application. Once you pack your app into JAR, file path will be like your/path/to/jar.jar!someResource - note ! mark (and that is what you would see as well). So basicly it will return File instance, you that you wont be able to use anyway, as file system has no access to it.
You could alternatively try to extract it first with ResourceUtiuls#extractJarFileURL(URL jarUrl) and then use extracted file.
I think, that in most cases Class#getResourceAsStream is the way to go and I think that it should fit your needs as well to read content of resource.

Relative path's to images and sound in 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.

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

Find resource in separate folder to class file

I'm trying to find a txt file in a separate folder to the class
Class file
C://workspace/project/src/pkg/Class.java
txt file
C://workspace/project/doc/pkg/myFile.txt
I'm trying to find the text file without having to hard code the C://workspace/project/ bit
Is this possible?
Currently I can use a classpath:/pkg/myFile.txt when the file is in the same package as Class.java using a resource loader
You could inclide the doc folder as a source folder. That way you can keep your resources separate from the code, but still have access to it using a classloader.
Of course that will only work for you when your resource can be part of the jar. If not, you may want to consider using a properties where you can configure the complete path to the resource.
Try getClass().getResource() or getClass().getClassLoader().getResource() if it is in the same jar-file

Categories

Resources