How to get resources from jar-files

Hi
in my app I load an image via the Toolkit.getImage() method.
Works fine if the app and the image are in folders on disk.
It fails to load the image, if the app (and the image) is packed in a jar file.
How can I get the image from there?
I try to get the image as follows:
String s = getClass().getResource("MyApp.class").getFile();
AppPath = s.substring(0,s.lastIndexOf("/"));
String PathToImages = "/images";
MyImage = (Image)Toolkit.getDefaultToolkit().getImage(AppPath+PathToImages+"/logo32.gif");The App starts and works, it just fails to load the images.
Any solutions??
thanx in advance
Herby

This is actually pretty easy. First a little background.
A Jar file is just a Zip file, with a few constructs for Java.
The getResource() method is used to create a mapping to data within the Jar file, but is actually not necessary after you know how the mapping works.
Just to give you an example of getResource:
// returned is a url to the resource you want from your Jar file.
URL myURL = MyClass.class.getResource("images/myimgage.gif");
// then you can use this URL to load the resource
Image img = getImage(myURL);If you were you look at the value of myURL you would see something similar to the followiing.
jar:http://www.mywebsite.com/mydir/myjarfile.jar!/images/myimage.gifJust to break it down for you.
The line always starts with the word jar:
Followed by the path to your jar file.
A sepearator !/
Then the file you are loading from the Jar file.
jar:     path_to_jar_file     !/     path_to_resource_in_jar_fileSo if you'd like, you could just create a URL object, and define the path to the object using the above method rather than using getResource.
Anyway, back to your code. What I would do is print out what you get for:AppPath+PathToImages+"/logo32.gif"I'm thinking you might be getting 2 "/" in your path because I think:AppPath = s.substring(0,s.lastIndexOf("/"));will leave the "/" at the end and the next line you add the "/" in front of the image directory name. So you my have the following for your image path.mypath//images

Similar Messages

  • Please help: Example how to peploy application from jar file step by step

    Please help: Example how to peploy application from jar file step by step.
    All help appreciated
    Mike

    Thanks I will try these links
    Mike
    "Slava Imeshev" <[email protected]> wrote:
    Hi Mike,
    These links could be useful:
    http://e-docs.bea.com/wls/docs61////adminguide/appman.html
    http://e-docs.bea.com/wls/docs61////quickstart/quick_start.html
    http://e-docs.bea.com/wls/docs61//////ConsoleHelp/application.html
    http://e-docs.bea.com/wls/docs61///programming/environment.html
    Regards,
    Slava Imeshev
    "Mike" <[email protected]> wrote in message
    news:3ca0e94c$[email protected]..
    Please help: Example how to peploy application from jar file step bystep.
    All help appreciated
    Mike

  • How to get Text from (.txt) file to display in the JTextArea ?

    How to get Text from (.txt) file to display in the JTextArea ?
    is there any code please tell me i am begginer and trying to get data from a text file to display in the JTextArea /... please help...

    public static void readText() {
      try {
        File testFile = new File(WorkingDirectory + "ctrlFile.txt");
        if (testFile.exists()){
          BufferedReader br = new BufferedReader(new FileReader("ctrlFile.txt"));
          String s = br.readLine();
          while (s != null)  {
            System.out.println(s);
            s = br.readLine();
          br.close();
      catch (IOException ex){ex.printStackTrace();}
    }rykk

  • How to get data from a file?

    Hello everyone, i'm new to this forum and to java too. Ok, so here is what i want to do:
    I want to get data from a file containing words and numbers and store them into variables that i will use them after to insert into a database table. For example i have a file called employees.txt in this form:
    eid ename zipcode Hire_date
    1000 "Jones" 67226 "12-DEC-95"
    In C++ i declare variables for each data and store them, for example in this case:
    ifstream in("somefile");
    string name, hdate;
    int eid, zip;
    in >> eid >> ename >> zip >> hdate;
    So i want to do the same thing in JAVA but i can't make it work. So, i would appreciate if someone could give me a simple example how to do it. Thank you.

    [http://java.sun.com/docs/books/tutorial/essential/io/index.html]

  • How to get path of jar file

    I am using a class which is present in a jar file.
    There are lot of versions of this jar file are present on machine.
    I am accessing one class from this jar.
    How do I know which jar is used by application.
    How to get the path(path on machine like c:\java\lib) of this jar file.

    URL jarURL = this.getClass().getResource("/whatever.class");will return you a jar:// URL. Experiment with that. (Remember that "whatever.class" needs to be prefixed by the full name of the package the class is in.)

  • How to get InputStream in jar file

    Could anyone give me a tip how I can play this sound file inside the application jar file?
    I have this package: *{color:#0000ff}com.sikgraf.ui{color}*
    with *{color:#ff6600}ArquivoMagneticoUI.class{color}* and {color:#ff6600}*applause.au*{color}
    I am tyring to get the InputStream but It's being painful and so far no success
    Here are the 3 ways I tried:
    InputStream is = ArquivoMagneticoUI.class.getResourceAsStream("applause.au");
    is = getClass().getResourceAsStream("applause.au");
    is = this.getClass().getClassLoader().getResourceAsStream("applause.au");All them return:
    java.lang.NullPointerException
            at java.io.FilterInputStream.mark(FilterInputStream.java:175)
            at com.sun.media.sound.WaveFileReader.getFMT(WaveFileReader.java:241)
            at com.sun.media.sound.WaveFileReader.getAudioInputStream(WaveFileReader.java:160)
            at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1094)What I am doing wrong?

    Thanks for your reply, I just figured out using URL:
        public static void playSound(int index) {
            String files[] = {"applause.au", "cash_register.au", "ding.au", "donkey_1.au", "duck_1.au", "siren_2.au"};
            String sound = "som/" + files[index];
            try {
                URL url = ArquivoMagneticoUI.class.getResource(sound);
                AudioInputStream ain = AudioSystem.getAudioInputStream(url);
                AudioFormat format = ain.getFormat();
                if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
                    format = new AudioFormat(
                            AudioFormat.Encoding.PCM_SIGNED,
                            format.getSampleRate(),
                            format.getSampleSizeInBits() * 2,
                            format.getChannels(),
                            format.getFrameSize() * 2,
                            format.getFrameRate(),
                            true);        // big endian
                    ain = AudioSystem.getAudioInputStream(format, ain);
                DataLine.Info info = new DataLine.Info(Clip.class, ain.getFormat(), ((int) ain.getFrameLength() * format.getFrameSize()));
                Clip clip;
                clip = (Clip) AudioSystem.getLine(info);
                clip.open(ain);
                clip.start();
            } catch (LineUnavailableException ex) {
                //Logger.getLogger(ArquivoMagneticoUI.class.getName()).log(Level.SEVERE, null, ex);
            } catch (UnsupportedAudioFileException ex) {
                //Logger.getLogger(ArquivoMagneticoUI.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                //Logger.getLogger(ArquivoMagneticoUI.class.getName()).log(Level.SEVERE, null, ex);
        }

  • How to load class from jar file dynamically?

    After I run my Java applicatoin, I need configuring the classpath of jvm to load some classess inside a jar file into the same jvm.How can I achive that?
    I mean, when I run my Java application, I don't know where the jar file is, what the jar file name is. All depends on the user to tell the jvm the details through some UI. I've tried to write: System.setProperty("java.class.path", "c:\myClass.jar");Class.forName("MyClass"); but failed.
    Can you tell my why and how?
    Thx

    After I run my Java applicatoin, I need configuring
    the classpath of jvm to load some classess inside a
    jar file into the same jvm.How can I achive that?
    I mean, when I run my Java application, I don't know
    where the jar file is, what the jar file name is. All
    depends on the user to tell the jvm the details
    through some UI. I've tried to write:
    System.setProperty("java.class.path",
    "c:\myClass.jar");Class.forName("MyClass"); but
    failed.That won't work. By the time it gets to your code it already has a copy of the original. You can't change it (short of modifying the JVM.)
    Can you tell my why and how?The usual way is to use a custom classloader.
    You can start by looking at java.net.URLClassLoader.

  • Resources from JAR files

    This is doubtless very simple stuff, but I nonetheless cannot figure out where I?m going wrong. I just need to open up some image files as icons in my program, and I?m trying to put all of the classes and resources in one jar file. I?m loading the image using getResource, and I have the images in a folder in the same place as my classes. Everything works fine when the files are separate, and the images load successfully. But then I put all the files into a jar (preserving the same hierarchy) and suddenly getResource returns NULL and of course the pictures don?t load. Is there anything else I ought to be doing?
    Many thanks,
    Ned

    Do any other ideas occur to anyone?Clearly there's a mismatch between the path used to reference the images, and the path where they live. This is pretty standard code, I've used it dozens of times, and I'm sure that the other responders have as well. On the surface, what you're doing looks right, so that only leaves one possibility.
    Two, actually: you aren't by any chance running this in an app-server or web-server?
    Assuming you aren't, put some debugging statements in, like this (not compiled, and I can't remember your image paths):
        URL resourceUril = this.getClass().getResource("/some/path/here");
        System.out.println("trying to load image from: " + resourceURL);This will print out a URL in the form jar:/some/path/here. Now display the contents of your jarfile, with jar tvf JARFILE. You'll see whether the path reported by the getResource() call is a valid path in your jarfile.

  • Help Me... How to get Data from CSV File...?

    Hi Everyone..!
    This is yajiv and am working in CS3 Photoshop platform. I know about Java Script. Is it possible to get the data from CSV files. Actually our client use to send us the CSV files which contains a lot of swatch name and reference files in one particular image name.
    Actually how we work on that CSV file is, first we copy file name to search that CSV file. then get the result to paste into layer name. This process continue till the end of swatch.
    Thank in Advance
    -yajiv

    > Is it possible to get the data from CSV files.
    Have you tried searching this forum?

  • How to get info from imported file in an outbound campaign IVR-based. UCCX 8.5.

    Hello.
    Somebody knows if it is possible to get the information inside my ivr script from the file imported when I create an outbound campaign IVR-based?
    I want to store in variable data like first name, last name, account number... And use them in the flow of my IVR script.
    I´m using UCCX 8.5.
    Regards

    did you get this to work ?

  • How to get list of jar files loaded by servlet container.

    Hi,
    I need to display in my servlet program about the list of jar files loaded by servlet container. Does it vary for each servlet container or is it same. Where can I get those details.
    I need to write code to support tomcat 4x, iplanet 5.0 and websphere 6.0.
    Thanks & Regards,
    Nasrin.N

    For curious, here are output prints for all 3 methods:
    1) parsing system property
    2) tschodt
    3) overcast SystemClassLoader to URLClassLoader
    /home/espinosa/workspace/jboss_embedded_test1/target/test-classes
    /home/espinosa/workspace/jboss_embedded_test1/target/classes
    /opt/javalibs/javax/ejb/ejb-api/3.0/ejb-api-3.0.jar
    /opt/javalibs/javax/jms/jms/1.1/jms-1.1.jar
    /opt/javalibs/javax/annotation/jsr250-api/1.0/jsr250-api-1.0.jar
    package com.sun.org.apache.xerces.internal.impl.validation, Java Platform API Specification, version 1.6
    package com.thoughtworks.qdox.directorywalker
    package com.sun.org.apache.xerces.internal.parsers, Java Platform API Specification, version 1.6
    package java.util.jar, Java Platform API Specification, version 1.6
    package org.testng.internal.thread
    package com.sun.org.apache.xerces.internal.util, Java Platform API Specification, version 1.6
    package java.net, Java Platform API Specification, version 1.6
    package sun.reflect.misc, Java Platform API Specification, version 1.6
    package esp.ejb.samples1.test
    package sun.security.provider, Java Platform API Specification, version 1.
    file:/home/espinosa/workspace/jboss_embedded_test1/target/test-classes/
    file:/home/espinosa/workspace/jboss_embedded_test1/target/classes/
    file:/opt/javalibs/javax/ejb/ejb-api/3.0/ejb-api-3.0.jar
    file:/opt/javalibs/javax/jms/jms/1.1/jms-1.1.jar
    file:/opt/javalibs/javax/annotation/jsr250-api/1.0/jsr250-api-1.0.jar
    ...Interestingly, method 1 and 3 gives the same list, same order, same count, just format of item is a little bit different. The order is same as in Eclipse .classpath file.
    Method 2 (tschodt) give significantly more items! rougly 3x! Different order (somewhat random it seems to me). Some items contain extra information, like version and string "Java Platform API Specification".
    It prints not absolute paths but logical Java names.

  • How to ban extracting from .jar file?

    Hello
    Problem of .jar file is: .class files can be extracted (with winrar ...) and decompiled. I don't want my classes to be decompiled. But I still need my jar executable of course.
    Is some solution which bans extraction without any impact on executability?
    Thank you very much.
    Tony

    Is some solution which bans extraction without any
    impact on executability?Hmmmm you could not put any class files in your jar. That would eliminate the extraction problem. Probably would be detrimental to execution.
    What do you think happens when your app runs? It just magically knows about your classes without extracting them?
    Not so much no.
    Use an obfuscator.
    Or if that's not good enough use another language or just panic.

  • How to get data from media files such author, title and so on

    Hi you all!

    You'd have to parse the binary file header yourself. JMF doesn't have any built-in ways to extract META data from media files.
    Also, don't post your question in the title and not in the body of the message. It's annoying and stupid...

  • How to get attribute from xml file

    I managed to grab all the info from xml, except the "url" attribute in <image type="poster" url="" size="mid" .../>. Any ideas?
    import java.io.*;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.net.*;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    public class XmlParser {
         ArrayList<Movie> myMovies;
         Document dom;
         public XmlParser(){
              //create a list to hold the movie objects
              myMovies = new ArrayList<Movie>();
         public void runExample(String adr, String tagName) {
              parseXmlFile(adr);
              parseDocument(tagName);
              printData();          
         private void parseXmlFile(String adr){
              //get the factory
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              try {               
                   //Using factory get an instance of document builder
                   DocumentBuilder db = dbf.newDocumentBuilder();
                   //parse using builder to get DOM representation of the XML file
                   URL xmlUrl = new URL(adr);
                   InputStream in = xmlUrl.openStream();
                   dom = db.parse(in);               
              }catch(ParserConfigurationException pce) {
                   pce.printStackTrace();
              }catch(SAXException se) {
                   se.printStackTrace();
              }catch(IOException ioe) {
                   ioe.printStackTrace();
         private void parseDocument(String tagName){
              //get the root elememt
              Element docEle = dom.getDocumentElement();
              //get a nodelist of <movie> elements
              NodeList nl = docEle.getElementsByTagName(tagName);
              if(nl != null && nl.getLength() > 0) {
                   for(int i = 0 ; i < nl.getLength();i++) {
                        //get the movie element
                        Element el = (Element)nl.item(i);
                        //get the Movie object
                        Movie mov = getMovie(el);
                        //add it to list
                        myMovies.add(mov);
          * I take an movie element and read the values in, create
          * an Movie object and return it
          * @param movE
          * @return
         private Movie getMovie(Element movE) {
              String title = getTextValue(movE, "original_name");
              String year = getTextValue(movE, "released");
              String imdbId = getTextValue(movE, "imdb_id");
              double score = getDoubleValue(movE, "score");
              String overview = getTextValue(movE, "overview");
              String poster = movE.getAttribute("url");
              Movie mov = new Movie(title, year, imdbId, score, overview, poster);
              return mov;
         private String getTextValue(Element ele, String tagName) {
              String textVal = null;
              NodeList nl = ele.getElementsByTagName(tagName);
              if(nl != null && nl.getLength() > 0) {
                   Element el = (Element)nl.item(0);
                   textVal = el.getFirstChild().getNodeValue();
              return textVal;
          * Calls getTextValue and returns a int value
          * @param ele
          * @param tagName
          * @return int
         private int getIntValue(Element ele, String tagName) {
              //in production application you would catch the exception
              return Integer.parseInt(getTextValue(ele, tagName));
          * Calls getTextValue and returns a double value
          * @param ele
          * @param tagName
          * @return double
         private double getDoubleValue(Element ele, String tagName) {
              return Double.parseDouble(getTextValue(ele, tagName));
          * Iterate through the list and print the
          * content to console
         private void printData(){
              System.out.println("Total Movies: " + myMovies.size());
              Iterator it = myMovies.iterator();
              while(it.hasNext()) {
                   System.out.println(it.next().toString());
         public static void main(String[] args){
              //create an instance
              XmlParser xp = new XmlParser();
              //call run example
              xp.runExample("http://api.themoviedb.org/2.1/Movie.search/en/xml/apikey/Fight+Club+1999", "movie");
    }Here is the example xml file I used
    <?xml version="1.0" encoding="UTF-8"?>
    <OpenSearchDescription xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">
      <opensearch:Query searchTerms="Fight Club 1999"/>
      <opensearch:totalResults>1</opensearch:totalResults>
      <movies>
        <movie>
          <score>8.383284</score>
          <popularity>3</popularity>
          <translated>true</translated>
          <adult>false</adult>
          <language>en</language>
          <original_name>Fight Club</original_name>
          <name>Fight Club</name>
          <alternative_name>El Club de la Lucha</alternative_name>
          <type>movie</type>
          <id>550</id>
          <imdb_id>tt0137523</imdb_id>
          <url>http://www.themoviedb.org/movie/550</url>
          <votes>62</votes>
          <rating>8.4</rating>
          <certification></certification>
          <overview>A lonely, isolated thirty-something young professional seeks an escape from his mundane existence with the help of a devious soap salesman. They find their release from the prison of reality through underground fight clubs, where men can be what the world now denies them. Their boxing matches and harmless pranks soon lead to an out-of-control spiral towards oblivion.</overview>
          <released>1999-09-16</released>
          <images>
            <image type="poster" url="http://hwcdn.themoviedb.org/posters/f75/4bc908ab017a3c57fe002f75/fight-club-original.jpg" size="original" width="1000" height="1500" id="4bc908ab017a3c57fe002f75"/>
            <image type="poster" url="http://hwcdn.themoviedb.org/posters/f75/4bc908ab017a3c57fe002f75/fight-club-mid.jpg" size="mid" width="500" height="750" id="4bc908ab017a3c57fe002f75"/>
            <image type="poster" url="http://hwcdn.themoviedb.org/posters/f75/4bc908ab017a3c57fe002f75/fight-club-cover.jpg" size="cover" width="185" height="278" id="4bc908ab017a3c57fe002f75"/>
            <image type="poster" url="http://hwcdn.themoviedb.org/posters/f75/4bc908ab017a3c57fe002f75/fight-club-thumb.jpg" size="thumb" width="92" height="138" id="4bc908ab017a3c57fe002f75"/>
            <image type="backdrop" url="http://hwcdn.themoviedb.org/backdrops/f71/4bc908ab017a3c57fe002f71/fight-club-original.jpg" size="original" width="1280" height="720" id="4bc908ab017a3c57fe002f71"/>
            <image type="backdrop" url="http://hwcdn.themoviedb.org/backdrops/f71/4bc908ab017a3c57fe002f71/fight-club-poster.jpg" size="poster" width="780" height="439" id="4bc908ab017a3c57fe002f71"/>
            <image type="backdrop" url="http://hwcdn.themoviedb.org/backdrops/f71/4bc908ab017a3c57fe002f71/fight-club-thumb.jpg" size="thumb" width="300" height="169" id="4bc908ab017a3c57fe002f71"/>
          </images>
          <version>73</version>
          <last_modified_at>2010-09-11 14:33:06</last_modified_at>
        </movie>
      </movies>
    </OpenSearchDescription>

    pvujic wrote:
    Thanks, but how can I "fetch" the url from the image element?You've got to first get to the image element. But based on what you've posted though, with a little more coding, you should be able to succeed. Just give it a try! :)

  • How to get InputStream from a file with absolute path?

    Hi, guys:
    If I have file with a absolute path that may be inside/outside
    my Eclipse plugin, I want to get an InputStream from it. It just keeps giving me null for "is":
    String absFilePath = "/D:/my_dir/.../sample_file.txt";
    InputStream is = getClass().getResourceAsStream(absFilePath);
    regards,

    Don't use resource as stream if you have an absolute path, use FileInputStream.

Maybe you are looking for

  • I'm getting the kernal panic screen when I put in DVD

    My iMac G5, 2 GB has been slow, and occasionally getting the "restart your computer" screen. I ran the Apple Hardware Test on it twice. It passed both times, so I decided it must be software. I proceeded to do a clean install of the OS. Now I'm getti

  • Purchase Order with Changable Condition types

    Dear gurus, I have the following requirement from our client: The Purchase order condition type must be changable after partial GR for  is done for the PO. that is the freight charges will be different for the Open quantity. How to configure this in

  • USB Printing - client-error-request-value-too-long

    A little while back, my iSight suddenly stopped working and so I did a full format and reinstall to 'fix' the problem. The problem wasn't 'fixed' through this action. Instead, I had to disconnect power and let the computer sit there for a bit and thi

  • Microsoft Programs quit.

    In our computer lab, We have 31 eMacs. The problem is that the microsoft programs keep quiting. We alaways have problems. We do never have good computers. Any ideas? Thanks

  • Total Pictures in Iphoto

    Can someone tell me how to get a count of all the pictures I have in Iphoto? I have checked and cannot seem to find how to tally all the pictures. Willy