Using resources in a jar file


















Your email address will not be published. Notify me of follow-up comments by email. Notify me of new posts by email. Skip to content Contents 1. Introduction 2. Packaging Resources 3. Loading the Resources 4. Overview of the technique: Packaging an application and all of its resources in a single runnable Jar file is clean and efficient.

However, the technique for successfully accessing images or other resource files inside of the jar from inside your code is not at all self evident until you hit on the general principle of how to do it: calling on the class loader for some class you are using which KNOWS where it's class is Here are a couple of code examples: Accessing a file as an input stream, e. Assume the file "properties. Here we tell the classloader to return the resource as a stream.

Accessing a resource file, e. The code here is just slightly different in that we simply ask the classloader to return us resource file directly. The example below shows how to create an image icon to illustrate the concept.

This does more or less make sense: it's supposed to be an archive , not some sort of database or pseudo-filesystem. But you mentioned a "src" folder Or does it mean that you're talking about how things are arranged in your IDE?

If it's the former, then you should start looking at how things are arranged in the jar file after you produce it instead. Tony Docherty wrote: As Paul has said if the code is running from the src folder and not from the jar then the contents of the jar will not be available unless you have explicitly added the jar file to the classpath used when the program is launched. I must say I've never tried to use getResource or getResourceAsStream when my classes haven't been in a package but I assume it works the same as if they are in a package.

Sorry for my apparent confusion. Are you saying I should put the Java code that accesses the text file or image resource into the JAR as well? Tony Docherty wrote: Sorry for my apparent confusion. Find the jar that contains your resources and your code should now work.

Getting a Resource from a JAR file. Mike London. Optional 'thank-you' note:. Hello, I see lots of posts that seem to say they're going to explain how to get a resource say a '. JPG' out of a JAR file using the code similar to the line of code I have below, but none of the examples actually seem to do it. Upon closer inspection, I find in every example I've looked at that they're just referring to a file in, say, a "resources" folder. Always "null". So my question is, what is the secret? Thanks very much for any suggestions!

Paul Clapham. I like If you want to use that code as is, then you put the jpg file into the same folder inside the jar as the file which is trying to use the jpg. Still confused. Yes, sorry, the "src" folder is just the IDE construct. This code is in a regular Java Application.



0コメント

  • 1000 / 1000