Images not loading after creating Jar - java

im wring a simple program and my images load in fine in the project but as soon as i export it into a jar file none of them load. i have little to no experiance creating artifacts or jar files.
project structure:
project:
src:
myclass1, myclass2...
res:
image1.png image2.png...
im using Toolkit.getdefaultToolkit to load in images
in my class i am loading the images in the constructor by writing
myImage = toolkit.getImage("res/image1.png");
this works perfectly fine in the project. does not work in the jar
i have also tried
myImage = toolKit.getImage("image1.png");
which does not work in the project or while opening the jar
i know toolkit is not the best way to go about loading images but i would like to know how i can fix this issue while using toolkit.
ive even tried using the absolute path to a folder on my desktop and once again they load in fine in my project but they do not get loaded when opening the jar. please help ive tried everything. thanks
(btw) if i open the jar file in intellij the images load but if i open the jar file in finder or from my desktop they do not. i want to be able to send the finished project to someone

The toolkit.createImage(String) method takes in a string, and interprets it as a path, looking for a file at that path. An entry in a jar file is not itself a file. It is therefore impossible to use this method to read image files that are in a jar.
However, that's not the only createImage method. There's also toolkit.createImage(URL) and that is the one you want.
SomeClass.class.getResource("something.png")
This expression works on any class (Foo.class gets you the class instance for Foo, and all class instances have the getResource method), and will look for the named entry in the exact same place SomeClass.class (the file) lives. If SomeClass.class currently lives in a jar file, then that's where it'll look.
Thus, ensure that img.png is in the same place your class file is (ensure it is jarred along with the rest), and that will work. You can also ask for e.g. SomeClass.class.getResource("/foo/bar/img.png"); this will then look from the 'root' of where SomeClass is. So if you have a jar such that if you run jar tvf thatjar.jar and you get:
....
/com/foo/yourpackage/SomeClass.class
....
/foo/bar/img.png
then /foo/bar/img.png works.
thus: Once you know where you put that stuff in your jar file:
toolkit.createImage(YourClass.class.getResource("image1.png"))
is what you're looking for.

Related

Getting location of file as string in resource folder

I have completed a program in eclipse and now I would like to export it as a single runnable jar file. The program contains a resource folder with images and text files in it. This is located beneath the source folder.
The res file is not added to the build path however when I run the program in Eclipse it still works.
The thing that is confusing me is that the res file is being saved into the runnable jar file when I export it as I can open the Jar file with WinRar and I see the folder is there with all the objects in it. But when I run the problem it stops at the point that the resource folder is referenced. To add to my confusion when I manually copy and paste the res folder next to where the runnable jar file is saved and run the program it works exactly as it should do.
Now I know this is something to do with how I reference the files in my code. At the moment I have it like this
reader = new LineNumberReader(new FileReader("res/usernames.txt"));
This works exactly how I want and accesses the res folder without any exceptions - in Eclipse and when I move the resource folder next to the Jar file.
I would like it to work normally but without having a folder outside of the Jar file I would like it all encapsulated in one Jar file.
I did a lot of research and what seems to be a common fix - may I add I don't really know how it works but everyone seems to mention it - is to somewhere use:
myClass().getResource()
When I create a new FileReader it needs a String input however when I use myClass().getResource() it returns a resource and not a string. I also don't have a clue how it is meant to reference the resource folder. Should I move the resource folder into the source folder?
Does anyone know how I can reference the resource folder from within the runnable jar file?
Sorry for rambling question I know what I want for my final product but I'm getting confused by the build paths and referencing from within classes and I have searched online for a long time trying to figure it out.
Resources, when you deploy your software, are not deployed as files in a folder. They are packaged as part of the jar of your application. And you access them by retrieving them from inside the jar. The class loader knows how to retrieve stuff from the jar, and therefore you use your class's class loader to get the information.
This means you cannot use things like FileReader on them, or anything else that expects a file. The resources are not files anymore. They are bundles of bytes sitting inside the jar which only the class loader knows how to retrieve.
If the resources are things like images etc., that can be used by java classes that know how to access resource URLs (that is, get the data from the jar when they are given its location in the jar), you can use the ClassLoader.getResource(String) method to get the URL and pass it to the class that handles them.
If you have anything you want to do directly with the data in the resource, which you would usually do by reading it from a file, you can instead use the method ClassLoader.getResourceAsStream(String).
This method returns an InputStream, which you can use like any other InputStream - apply a Reader to it or something like that.
So you can change your code to something like:
InputStream is = myClass().getResourceAsStream("res/usernames.txt");
reader = new LineNumberReader( new InputStreamReader(is) );
Note that I used the getResourceAsStream() method from Class rather than ClassLoader. There is a little difference in the way the two versions look for the resource inside the jar. Please read the relevant documentation for Class and ClassLoader.

Loading image from a Java file

I have this project structure:
ProjectName
src
xxx
co
com
package
something.java
web
image
print
pic.jpg
I want to load the pic.jpg in the java file which will then be used in the pdf file generated. I have gone through the answers here but, nothing helped me yet. Possibly I am missing a small thing.
If the pic.jpg was under package, then getClass().getResource("pic.jpg") works absolutely fine. getClass().getResource("/web/image/print/pic.jpg") doesnt work as well. But I want to place all my images under image folder and refer it in the java file.
You should get the application runtime path and rebase the path to the folder which images locate.
You can use the code:
String path = new File(".").getCanonicalPath();// or System.getProperty("user.dir")
Seems your files are not copied to bin/ directory. Change your build script to copy them to output directory
getClass().getResource() will use class loader to load class, since those files need to be in classpath

Problems with loading CLP file from JAR

I am using CLIPSJNI.
What I have is:
Environment clips = new Environment();
clips.load("main.clp");
where main.clp is put in the same level as src and bin folder.
This runs fine in Eclipse. However when I export to JAR. It cannot work.
I understand that there are some problems with the path when we export to JAR.
So I've seen people suggesting using this.getClass().getResourceStream() but this is not the case. Because what I need is the name of the file, not its content.
Any suggestions on how to fix this?
The issue is that the load is being done within the native library on the C side which is being passed a file name as an argument. The C code has no concept of a JAR file or how to extract files embedded within one. I think what you would need to do is always place your .clp files within the JAR file and then have a routine which extracts the data from the JAR file and saves it to a file. You can then load it using the load method and delete the file once done.

Find a resource both in .jar and eclipse with the same String computation

I want to get the path to a resource for ImageIO to read out a BufferedImage from some .png s.
While developing the project I use a relative path to "/bin/stuff/icons/image.png" , but this will definetly not work when I put everything together into a .jar file, so I need a way to get the path to these resources both while testing in eclipse and when later running it within a .jar .
After a lot of trying out both finding the file and getting the input stream to the file I came to the conclusion that this approach works every time:
InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(path)
BufferedImage image = ImageIO.read(in)
Where path is
"projectName/resourceFolder/" + nameOfResource.stuff
as found in the src directory of the eclipse project.
E.g.
"myProject/images/icon.png"
When getting only the resource and then getting the path of the resource to link to a file, you will get FileNotFoundExceptions when using a .jar (but not while testing with eclipse, so one should be warned to think that his code works).
And - no - I don't save images in the bin/ - but they are copied to this directory and thus I find them there while testing. Now everything seems to be working.
Don't put anything under the bin directory in Eclipse: if you run a clean on the project it will be erased.
What you can do is to define a new source folder like resources, and put the image there. This way it will be automatically copied to the bin folder.
If you include the resources folder into the Jar, it will be available in both environments by using something like:
ImageIO.read( getClass().getResource("/image.png") )
PS: You can evade using a different resources folder but mixing the sources and images will quickly pollute your source folder.

Applet: Loading image in jar file that is not in home directory

this title may sound confusing so I'll explain my problem.
I am converting my java application to an applet, and it works fine in Eclipse and when I make a html file with tags. But when I upload my applet to google sites and execute it via a html file, the program itself loads fine, but it tries to load its images from my own hard disk instead of from the JAR file. How can I change that?
HTML:
<applet
archive="https://sites.google.com/site/projectteagame/tea.jar"
code="ymte.core.Loader"
width=300
height=300> </applet>
Edit:
I keep all my files in the jar, for speed and ease. My code to obtain the images is:
img = ImageIO.read(Loader.class.getResourceAsStream("/res/object/ball.bmp"));
This works in my IDE, but not in the online use
You can provide your code to tell us how you obtain the image, but I suppose it is not bundled in the jar. A way to do that is to put the jar in your packages and obtain it like this:
Class.getResourceAsStream("foo");
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)
This is kinda gimmicky, however. A preferred way would be to put your image into a directory in your project that is outside your sources, something like images or resources and then bundle it in the jar of the applet. Use your favorite build tool (ant, maven, ivy) to include the image in the jar. Directory structure can be like this:
project
-src
-resources
-<yourImage>
Then you would access your image as a URL or File using a relative path. If you provide more code, maybe you can receive further help.
EDIT:
SInce your resource is in your applet, you can put it in one of your packages. Then, further in your code you can do
Class.getResourceAsStream
and that is how you can get your image, since it is guaranteed to be in your classpath.
Basically, if you have a package structure like this:
project src
com.foo.bar
com.foo.bar.stuff
com.foo.bar.resources
-yourImage
-otherStuff
-ResourceGetter.java
You can do the following in your ResourceGetter
Class.getResourceAsStream("yourImage");
Which will give you a handle to your image and you can load it as you would do normally.

Categories