How to access images within a .Jar File - java

I've been trying for a couple of days to access an image within a .Jar file. I've taken a look at several solutions on this site and nothing seems to be working for me. I've tried several instances of the code included below, using URL and inputStreams, with full path names, reduced path names, and automating the path names using system.getProperty("user.dir"); I've tried alternating between forward and backslashes, doubling up on backslashes and the like.
I also understand that accessing an image in a .jar is not the same as locating a file and it's path.
Code I've tried using:
url = getClass().getResource("/ball.PNG");
try {
image = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
}
try {
image = ImageIO.read(this.getClass().getResource("/ball.PNG"));
if (image == null){
System.out.println("Could not find image for the ball!");
}
catch (IOException e) {
e.printStackTrace();
}
InputStream input = getClass().getResourceAsStream("ball.PNG");
try{
image = ImageIO.read(input);
}
catch(IOException e){
e.printStackTrace();
}
None of these solutions are working. compiling and running works just fine. The jar file is made just fine, and when I look inside, the PNG I used is included. Actually running the .Jar file gives me the error "Exception in thread "main" java.lang.IllegalArgumentException: input == null!" along with a few more lines that just indicate that errors occur when trying to pull information from the image.
The most interesting part to me is that most of these solutions work in some form or another when running the .class files, but none work for the .jar file.
For more context, the variable image is a BufferedImage; I've been using Notepad++ and command prompt to run, compile and create the .class and .Jar without issues. There is no subdirectory for the image files, and again after checking, they are included in the .jar file. I have no idea why the .class files can find the images and use them but the .jar files cannot.
I know the code isn't pretty to look at and a bit incomplete, but keep in mind that these are just quick examples I've written up. Compiling and running works just fine, as does running the jar files. Only the .jar file has trouble locating the image file. I've looked at these threads and used their examples to form my code:
Using png in a jar file
Access .png image in .jar file and use it
Some edits others have asked for:
A picture of the files and their location
A picture of the command "jar tf BallGame.jar"
posted in a code block:
C:\Users\Phili\Documents\TheBallGame>jar tf BallGame.jar
META-INF/
META-INF/MANIFEST.MF
Ball.class
BallGame$1$1.class
BallGame$1$2.class
BallGame$1.class
BallGame.class
Coin.class
gamePanel.class
GlobalConstants.class
RedBall.class
ball.png
coin.png
Distances and stuff.png
redBall.png
A picture of what is actually inside the jar file.

Related

how to make jar file to load images on run time

i am loading buffered image in java through the following lines of code and it works good and when i clean and build this code .jar file is created which also loads the same file.but now if replace the picture in src folder the jar file still loading the old one picture.
i want that once i clean and built my program the jar file can load images that are currently available.
is there any solution for that or any other file extension that runs my program without using idle but loads images at run time.
try {
return ImageIO.read(imageloader.class.getResource(path));
} catch (IOException ex) {
Logger.getLogger(imageloader.class.getName()).log(Level.SEVERE,
null, ex);
}
Using Class.getResource() loads file from the classpath.
So I suppose the your jar contains the image file (because it is in the src folder), and your program loads the file from the jar. Not from an src folder anywhere else !
HTH,
This is how to load an image from file:
File file = new File("Pass the image file location here")
BufferedImage image = ImageIO.read(file)

(Java) Trouble going between URLs and files with a .jar file

I'm making a rather big program in java. It has lots of files, including images, audio, and text files. When I'm running from Eclipse, the code I use works fine. However, I always have trouble gaining access to them from a .jar file that's on its own.
I'll give you an example of how I'm coding this.
For the BufferedImage, I have it this way:
File bgImgFile = new File("images/nature.jpg");
BufferedImage bgImg = ImageIO.read(bgImgFile);
For the AudioInputStream, I have:
File soundFile = new File("audio/two.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
And for the text file, I have:
FileReader reader = new FileReader("scripts/0.txt");
This all works fine for when I'm in Eclipse. However, I'm thinking about what I'll want to do for distribution. I want to have a .jar file that can run anywhere, and doesn't need to be in the same directory as those folders containing the files. I've done this before and it's worked fine.
This is what I tried to do for the image:
URL bgFileUrl = MainClass.class.getClassLoader().getResource("images/nature.jpg");
File bgImgFile = new File(bgFileUrl.getFile());
BufferedImage bgImg = ImageIO.read(bgImgFile);
I did similar things for the audio and text file. However, even when I tried in different combinations of having the files themselves in the same directory, having a slash in front of the plain file name, etc., nothing worked. I want to be able to include these files in the .jar file so I don't have to run the .jar from that specific folder.
One thing I don't understand is that, when I opened up the .jar file made using my original code, the images, audio, and scripts folders were in there and they had my files. They were there. However, when I tried to run it, I got an IIOException ("Can't read input file!") and a NullPointerException, even though I was using the same code as before.
How do I make it so the files are included in the .jar file so it can run on its own?
Thanks for the help!
Can you try below code
URL audioFileUrl = MainClass.class.getClassLoader().getResource("audio/two.wav"");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(audioFileUrl);

In netbeans, how to save or access an image after deploying jar file

I am trying to make a mess management application in Java using NetBeans. I want to save images of Members in a specified folder inside my src directory. I just created folder named EmpImgs for storing employees images. Here is my code:
File srcDir = new File(file); // current path of image
File dstDir = new File("src\\J_Mess_Mgnt\\EmpImgs\\"+Txt_C_G_M_M_ID.getText());
objm.copyFile(srcDir, dstDir);` // copy image from srcDir to dstDir
Here I use another class for copying images to predefined folders and renaming the images based on their ID.
Everything is working properly in Java IDE.
But unfortunately after making an executable .jar file, this code will not work. I cannot save or access any image file in that directory.
I just went through this site, but I didn't find a suitable answer.
All I need is saving and editing images inside jar folder
Hehe hi mate you need some help. This is a duplicate but I will cut you some slack and maybe you should delete this later. So back to basics, the jvm runs byte code, which you get from compiling java source code to .class files. Now this is different to C and C++ were you just get a .exe. You don't want to give your users a bunch of .class files in all these folders which they can edit and must run a command on the command line, but instead give them what is known as an 'archive' which is just an imutable file structure so they can't screw up the application, known as a jar in java. They can just double click on the archive (which is a jar), and the jvm will call the main method specified in the MetaInf directory (just some information about the jar, same as a manifest in other programming languages).
Now remember your application is now a jar! It is immutable! for the resasons I explained. You can't save anymore data there! Your program will still work on the command line and in IDEs because it is working as if you used your application is distrubuted as bunch of folders with the .class files, and you can write to this location.
If you want to package resources with your application you need to use streams (google it). BUT REMEMBER! you cant then save more resources into the jar! You need to write somewhere else! Maybe use a user.home directory! or a location specified from the class path and the photos will be right next to the jar! Sometimes you might need an installer for your java application, but usually you don't want to create the extra work if you don't need to.
At last I find an answer suit for my question.It is not possible to copy images or files to a executive jar folder.So I used a different Idea.Create some folders(as per our requirement),Where my executable jar folder is located(No matter which drive or where the location is).The code is..
String PRJT_PATH=""; //variable to store path of working directory.
private void getdire() throws IOException{
File f=new File(".");
File[] f1=f.listFiles();
PRJT_PATH=f.getCanonicalPath(); //get path details.for eg:-E:/java/dist
}
private void new_Doc_folder(){ //function for creating new folders
try{
String strManyDirectories="Docs"+File.separator+"Bil_Img"; //i need to create 2 folders,1st a folder namedDocs and In Docs folder another folder named Bil_Img
String SubDirectories="Docs"+File.separator+"EmpImgs"; //same as above but keep in mind that It will not create a Same folder again if already exists,
// Create one directory
boolean success = (new File(strManyDirectories)).mkdirs(); //create more than one directory
boolean success1 = (new File(SubDirectories)).mkdir(); //Creates a single directory
if (success && success1) {
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
It works Successfully.
Regds

Can't load resources when running the code from an executable JAR

I'm having this problem where none of the resources load when I run a JAR of the program. I've changed code and checked that it is indeed both the code that loads images and the code that loads sounds do not work. It works perfectly fine when I run it in eclipse. I checked with 7-Zip and the sounds and images files aren't in a res folder anymore. I tried changing the path files and the location of the resources in my program before I exported it, but that didn't work. I also have the res folder as a source folder in the build path. I'm exporting the JAR with eclipse, and then adding my libraries into it with JarSplicer. Here are the codes that load images and sound resources:
-Load Sound-
public static WaveData LoadSound(String path){
WaveData sound = null;
try {
sound = WaveData.create(new BufferedInputStream(new FileInputStream(path)));
} catch (Exception e) {
e.printStackTrace();
}
return sound;
}
-Load Images-
public static Texture LoadTexture(String path, String fileType){
Texture tex = null;
InputStream in = ResourceLoader.getResourceAsStream(path);
try{
tex = TextureLoader.getTexture(fileType,in);
}catch(IOException e){
e.printStackTrace();
}
return tex;
}
Here's my error in the command prompt:
Here are the files in the jar every time I exported it (regardless of whether the resources were in res or not):
I'm stumped here. If someone knows how to fix this, then please help me out.
I found the answer to my problem.
ResourseLoader.getResourceStreamAs() does not work inside of JAR files, so you need to do getClass().getResourceStreamAs(), or [ClassName].class.getResourceStreamAs(), if it's static.
Also, I had to change the location of the files from res/[resource file]/[resource] to /[resource file]/[resource] because when you export, it takes out all of the files in res. Also, you have to make sure that you have that / at the beginning of the path there in order to designate it to search in the source folder, or else it will search in the folder of the class that called getResourceStreamAs(). And also, new FileInputStream() doesn't work in JAR files, so you have to use [ClassName].class.getResourceStreamAs() instead. Oh, and on top of that, I had a few files that somehow got the extension part its name in all capitals for no reason. So that gave me some confusion. I basically just had to do a bunch of fiddling with code, but I got it working!
One more thing: make sure you add your resources folder to the sources tab in the build path, or else eclipse won't export it. And if you want your libraries to be exported in your JAR, then you'll have to add them manually by making a fat jar with JarSplicer.
Turns out that paths to resources are case sensitive and do not work in jar files if there is a single misstyped letter in the path.

Images not shown while running the JAR created by Eclipse

I have my images folder inside source folder in my Eclipse IDE
After exporting the application into a runnable JAR, I run it through command prompt, but it does not display any images that I have used. When I run it through Eclipse, images are displayed.
And when I copy the source/images folder to where my executable JAR is, then it shows images, but I want my images also to be in JAR itself.
What is the problem?
public BufferedImage loadImage(String fileName){
BufferedImage buff = null;
try {
buff = ImageIO.read(getClass().getResourceAsStream(fileName));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return buff;
}
Your images should NOT be in your source folder. You should hold them separate in another folder (assets or ressources or images or so).
To include the folder in your jar, I highly suggest using ANT script (or maven) to generate your jar. Its much more flexible. It takes a bit to get the grasp on it, but there are a lot of examples and tutorials around and I think its definitely worth it.

Categories

Resources