Read images from external jar file (Sun's Java L&F Graphics repository)

Hi!
I don't know how to read images from an external jar file. Sun has a Java Look and Feel graphics repository that contains a lot of good images that can be used on buttons and so on. This repository is delivered as a jar file, containing only images, and I want to read the image files from that jar file directly without including them inside my application jar file. The application and image jar files will be in the same directory.
I have absolutely no clue how to solve this. Is it necessary to include the images inside my application jar file or is it possible to have them separate as I want.
Would really appreciate some help!
Best regards
Lars

Hi,
There is two ways :
1) Add your jarfile to the classpath.
Use the class loader :
URL url = ClassLoader.getSystemResource("your/package/image.gif");
Image im = (new ImageIcon(url)).getImage();
or
Image im = Toolkit.getDefaultToolkit().getImage(url);2)If you don't want to add the jar to the classpath you can use this (under jdk 1.4):
import java.util.*;
import java.util.jar.*;
import java.awt.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class ImageUtilities {
     public static Image getImage(String jarFileName, String fileName) {
          BufferedImage image = null;
          try {
               JarFile jar = new JarFile(new File(jarFileName), false, JarFile.OPEN_READ);
               JarEntry entry = jar.getJarEntry(fileName);
               BufferedInputStream stream = new BufferedInputStream(jar.getInputStream(entry));
               image = ImageIO.read(stream) ;
          catch (Exception ex) {
               System.out.println(ex);
          return(image);
}I hope this helps,
Denis

Similar Messages

  • Read images from a jar file?

    Hello, I'm converting a 6i app to 10g. This app does a ton of read_image_file() calls to
    change GIF images on the screen based on user actions. In 6i the images are all stored on the local hard drive. The images are not icons for buttons, but images that appear in different locations on the screen.
    For 10g, is it possible to leave the images in a jar file and effectively read the images from that? Otherwise, I suppose I'm looking at using webutil functionality to download the jar file and unjar it into an images directory for reading from the client?
    Any best-practice scenario for this sort of thing?
    Thanks for any info,
    Gary

    We are migrating from 6i to 10g too. And I try to not use webutil. All my pictures (icons gif files) are in a jar file.
    Just make attention of the size of your pictures. The jar file is loaded when you launch the application (the first time, and after, only if the jar file has changed).

  • Issues with Loading Images from a Jar File

    This code snippet basically loops through a jar of gifs and loads them into a hashmap to be used later. The images all load into the HashMap just fine, I tested and made sure their widths and heights were changing as well as the buffer size from gif to gif. The problem comes in when some of the images are loaded to be painted they are incomplete it looks as though part of the image came through but not all of it, while other images look just fine. The old way in which we loaded the graphics didn't involve getting them from a jar file. My question is, is this a common problem with loading images from a jar from an applet? For a while I had tried to approach the problem by getting the URL of the image in a jar and passing that into the toolkit and creating the image that way, I was unsuccessful in getting that to work.
    //app is the Japplet
    MediaTracker tracker = new MediaTracker(app);
    //jf represents the jar file obj, enum for looping through jar entries
    Enumeration e = jf.entries();
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    //buffer for reading image stream
    byte buffer [];
    while(e.hasMoreElements())
    fileName = e.nextElement().toString();
    InputStream inputstream = jf.getInputStream(jf.getEntry(fileName));
    buffer = new byte[inputstream.available()];
    inputstream.read(buffer);
    currentIm = toolkit.createImage(buffer);
    tracker.addImage(currentIm, 0);
    tracker.waitForAll();
    images.put(fileName.substring(0, fileName.indexOf(".")), currentIm);
    } //while
    }//try
    catch(Exception e)
    e.printStackTrace();
    }

    compressed files are not the problem. It is just the problem of the read not returning all the bytes. Here is a working implementation:
    InputStream is = jar.getInputStream(entry);
    ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
    try{
    byte[] buf = new byte[1024];
    int read;
    while((read = is.read(buf)) > 0) {
    os.write(buf, 0, read);
    catch(Exception e){
         e.printStackTrace();
         return null;
    image = Toolkit.getDefaultToolkit().createImage(os.toByteArray());
    This works but I think you end up opening the jar a second time and downloading it from the server again. Another way of getting the images is using the class loader:
    InputStream is = MyApplet.class.getResourceAsStream(strImageName);
    In this case, the image file needs to be at the same level than MyApplet.class but you don't get the benefit of enumerating of the images available in the jar.

  • ? SplashScreen - retrieving an image from a jar file ?

    When you want to use the Java SplashScreen you provide a run flag of the form:
    -splash:image.png
    Is there a way to have the 'image.png' reference a file in one of the jar files?I don't believe the jar files are loaded by the time SplashScreen activates so that might be why I can't seem to be able to do it, but that was when I checked over a year ago ... have things changed?
    Alternatively (and probably the preferred option for me) is there a way to tell the SplashScreen to create an empty splash so that one exists when I use the 'splash.setImageUrl()' method? Currently I have to set the splash image to be some empty/transparent image via:
    -splash:empty.png
    Then I set my own desired image via the 'splash.setImageUrl()' method...BUT, I still need to have the 'empty.png' file contained in the root folder of my project and this sucks. I'd like to be able to tell java that I want to create an empty splash, without having to provide an empty image, and then when the splash is created, I can use the image url method as normal to write my own image to the splash display.
    thx.

    morgalr, this is independent of code, it's just the splash screen that start up before any code runs so you could do this with any of your projects that you have.
    You need to specify splash image via run command of:
    -splash:image.png
    so, if you have a jar file that has an image in it, and you place it on your classpath and then try to run your code with
    -splash:package/path/image.png
    it doesn't seem to work...you'll know because either you'll see a splash screen or you won't. Note that the splash screen disappears the first time an AWT/Swing event is encountered (ie a frame is displayed, etc) so it may only last a few milliseconds but it still should come up. All of the links that discuss this talk about specifying a path to an images directory, but this images directory has to be in your project root folder and not in the source tree (as best as I can tell through experimentation).
    I guess what I would ultimately want would be to be able to create a SplashScreen instance through each program in my project without having to provide a runtime flag that only generates the instance if the provided image is available. If I it still provided a SplashScreen instance then I would be able to use the setImageUrl() method from code to provide the desired image. Also, it would be nice if the splashscreen remained some set time even after the application window popped up with an AWT/Swing event that now causes it to disappear instantly...but that one I can overcome with my own JWindow post-splash display that mimics the effect.
    thanks.

  • Loading images from a jar file

    Hi,
    My application displays images, until it's placed in a JAR file, then it can't display them even though the JAR file contains the images.
    I saw this problem in a previous question which was solved using
    URL url = MyClass.class.getResource("abc.gif");
    Image img=Toolkit.getDefaultToolkit().getImage(url);
    ....which btw didn't work for me either......
    This method should be made obsolete using ImageIcon, which I am using, but the images still won't appear...
    Any suggestions?

    It works fine that way (...getClass().getResource....) until I create the jar file, and then I get a null pointer exception when it tries to load the image.
    When I use
    javax.swing.ImageIcon icon = new javax.swing.ImageIcon(("/images/imageName.jpg"));
    the application works but without the images.......

  • How to access Shared Component Images from External Javacript File

    Hi,
    I have an external javascript file that is referenced within a page that consists of a number of calls to images within the Shared Components, i.e.:
    "#WORKSPACE_IMAGES#up_arrow.png"
    Unfortunately this no longer seems to work when used in an external js file.
    What options do I have to allow the external js to access images within the Shared Components/database?
    Thanks.
    Tony.

    Hi,
    You do not have much options, that is know limitation.
    This post is about same kind problem with CSS files
    Re: referencing workspace image in CSS file
    Br,Jari

  • Reading Images from JAR Files

    Hi,
    I am having a very difficult time being able to read images from a JAR file via my Applet. I have tried everything that I know about with no luck. The only way I can get this to work is to store the images individually in a sub directory of public_html on the websever. This works, but I would like the images to come down in a JAR file for performance reasons.
    I am using Internet Explorer 5.5 for my browser. I checked the options and everything seems to be in order, but......
    I would appreciate any feedback that anyone might have on this topic..........
    Thank You....

    once in a jar file i inserted a image
    the jar file on clicking starts an frame.
    so the image was for getting that image at the icon place at top and at minimized window
    i could not get that image from jar file by new imageicon().getimage();
    but i get the image if it is in the directory in which jar file is.....
    can one explain the reason

  • Reading an xml file from a jar file

    Short question:
    Is it possible to read an xml file from a jar file when the dtd is
    placed inside the jar file? I am using jdom (SAXBuilder) and the default
    sax parser which comes with it.
    Long Question:
    I am trying to create an enterprise archive file on Weblogic 6.1. We
    have a framework that is similar to the struts framework which uses it's
    own configuration files
    I could place the dtd files outside the jar ear file and specify the
    absolute path in an environment variable in web.xml which is
    configurable through the admin console.
    But I want to avoid this step and specify a relative path within the jar
    file.
    I have tried to use a class which implements the entityresolver as well
    as try to extend the saxparser and set the entity resolver within this
    class explicitly, but I always seem to sun into problems like:
    The setEntityresolver method does not get called or there is a
    classloader problem. i.e. JDOM complains that it cannot load My custom
    parser which is part of the application
    Vijay

    Please contact the main BEA Support team [email protected]
    They will need to check with product support to determine
    the interoperatablity of Weblogic Server with these other
    products.

  • How to add multiple images to a JLabel from the jar file

    I want to add multiple images in a JLabel but the icon property only allows me to add one. I thought I could use html rendering to add the images I need by using the <img> tab, but I need to use a URL that points to the image.
    How do I point to an image inside the jar file? If I can't, is there another way to show multiple images in a JLabel from the jar file?

    Thanks, it works perfectly. It's a really smart way of fixing the problem too :)
    I also found your toggle button icon classes which is something I've also had a problem with.
    Thanks.

  • Urgent help for processing XML stream read from a JAR file

    Hi, everyone,
         Urgently need your help!
         I am reading an XML config file from a jar file. It can print out the result well when I use the following code:
    ===============================================
    InputStream is = getClass().getResourceAsStream("conf/config.xml");
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line;
    while ((line = br.readLine()) != null) {
    System.out.println(line); // It works fine here, which means that the inputstream is correct
    // process the XML stream I read from above
    NodeIterator ni = processXPath("//grid/gridinfo", is);
    Below is the processXPath() function I have written:
    public static NodeIterator processXPath(String xpath, InputStream byteStream) throws Exception {
    // Set up a DOM tree to query.
    InputSource in = new InputSource(byteStream);
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setNamespaceAware(true);
    Document doc = dfactory.newDocumentBuilder().parse(in);
    // Use the simple XPath API to select a nodeIterator.
    System.out.println("Querying DOM using " + xpath);
    NodeIterator ni = XPathAPI.selectNodeIterator(doc, xpath);
    return ni;
    It gives me so much errors:
    org.xml.sax.SAXParseException: The root element is required in a well-formed doc
    ument.
    at org.apache.xerces.framework.XMLParser.reportError(XMLParser.java:1213
    at org.apache.xerces.framework.XMLDocumentScanner.reportFatalXMLError(XM
    LDocumentScanner.java:570)
    at org.apache.xerces.framework.XMLDocumentScanner$XMLDeclDispatcher.endO
    fInput(XMLDocumentScanner.java:790)
    at org.apache.xerces.framework.XMLDocumentScanner.endOfInput(XMLDocument
    Scanner.java:418)
    at org.apache.xerces.validators.common.XMLValidator.sendEndOfInputNotifi
    cations(XMLValidator.java:712)
    at org.apache.xerces.readers.DefaultEntityHandler.changeReaders(DefaultE
    ntityHandler.java:1031)
    at org.apache.xerces.readers.XMLEntityReader.changeReaders(XMLEntityRead
    er.java:168)
    at org.apache.xerces.readers.UTF8Reader.changeReaders(UTF8Reader.java:18
    2)
    at org.apache.xerces.readers.UTF8Reader.lookingAtChar(UTF8Reader.java:19
    7)
    at org.apache.xerces.framework.XMLDocumentScanner$XMLDeclDispatcher.disp
    atch(XMLDocumentScanner.java:686)
    at org.apache.xerces.framework.XMLDocumentScanner.parseSome(XMLDocumentS
    canner.java:381)
    at org.apache.xerces.framework.XMLParser.parse(XMLParser.java:1098)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.
    java:195)
    at processXPath(Unknown Source)
    Thank you very much!
    Sincerely Yours
    David

    org.xml.sax.SAXParseException: The root element is required in a well-formed document.This often means that the parser can't find the document. You think it should be able to find the document because your test code could. However if your test code was not in the same package as your real (failing) code, your test is no good because getResourceAsStream("conf/config.xml") is looking for that file name relative to the package of the class that contains that line of code.
    If your test code wasn't in any package, put a slash before the filename and see if that works.

  • Dynamic Internal Table for reading data from external file

    Hello All,
    The task was to create a internal table with dynamic columns,
    Actually this is my first task in the WebAS 6.20, my program is based on input file provided by user with certain effort. this file can have different effort for a one yr to five year frame..
    I needed to read the raw data from file, based on months create a internal table to hold the data, after this i need to validate the data...
    I have browsed thru dynamic internal table topic, but couldn't find any dynamic appending structure, the dynamic structure would contains 12 month fileds.
    can any one help me in getting my task completed..
    Thanks
    Kumar

    Hi,
    I see that you posted the same question a couple of days ago at Dynamic Internal Table for reading data from external file Didn't Charles's response address your problem?
    Regards

  • How to read a text file from a Jar file

    Hi
    How can I read a text file from a Jar file?
    Thanx in advance..

    thanx
    helloWorld it works.damn, I didn't remove it fast enough. Even if it is urgent, it is best not to mention it, telling people just makes them take longer.

  • How to call external jar files in EJB project for CE

    Hi,
    I would be thankful if someone could help me with this -
    I need to call the external jar files into my EJB project - Here is what I have done and am getting runtime exception as  -
    java.lang.RuntimeException: java.lang.NoClassDefFoundError: com/glance/pdf/pt/PTDoc
    1. Created a EJB  project" HelloWorld "  using Java perspective in NWDS 7.1 called with client as HelloWorldClient and EAR project as HelloWorldEAR.
    2. Am working on HelloWorld project (1st one).
    3. In my code I am instantiating a class which is a class in one of  the external jar file that I need to refer in my project.
    4. I have set the Java Build path but it works only for the compile time and fails during runtime.
    5. Have read I need to create external library DC and refer in my project "HelloWorld".
    Can anyone help me with exact steps what needs to be done - during creation of external library project and then for my "HelloWorld" EJB project. How would I be able to reference or set the external library project in my EJB project?
    Looking forward to hear from experts.
    Thanks,
    Shiv
    Edited by: Shiv Khullar on Aug 30, 2010 9:39 PM

    Hi Edson,
    I tried it , but it still gives me runtime exception.
    javax.ejb.EJBException: nested exception is: java.lang.RuntimeException: java.lang.NoClassDefFoundError: com/glance/pdf/pt/PTDoc
    java.lang.RuntimeException: java.lang.NoClassDefFoundError: com/glance/pdf/pt/PTDoc
    Steps I performed are -
    1. Created a library project and created 2 Public parts "Compilation" and "Assembly"
    2. Build the library project.
    Now in my EJB project using Project Explorer - set the classpath and added both compilation jar and assembly jar files.
    This is how the classpath entries for external library looks like -
    <classpathentry kind="lib" path="/LocalDevelopmentLocalDevelopmentexternallibrarypdftoolsforwatermarkingdemo.sap.com/gen/default/public/WatermarkAssembly/lib/java/demo.sap.comexternallibrarypdftoolsforwatermarking~WatermarkAssembly.jar"/>
         <classpathentry kind="lib" path="/LocalDevelopmentLocalDevelopmentexternallibrarypdftoolsforwatermarkingdemo.sap.com/gen/default/public/WatermarkCompilation/lib/java/demo.sap.comexternallibrarypdftoolsforwatermarking~WatermarkCompilation.jar"/>
    I have also added the jar files I used in my external library project as "User Library" from Java Build Path . I dont do it , then the code fails during compilation itself.
    Regards,
    Shiv

  • Executing .jar files from another .jar file.

    How would I run one .jar file from another .jar file. and is there anyway to call specific class arguments? Because I have one .jar file that reads a specified file and returns its contents.
    So how would I execute it and specify its arguments and how would I make it return something to the executing jar file?

    Because I have one .jar file that reads
    a specified file and returns its contents. Presumably you have a class that does that, and you have that class stored in a jar. And you want to know how to... um... do something with that class. I say "um..." because normally you don't execute a class, either, you either call its static methods or you create an instance of the class and call its instance methods.
    If you have been writing a whole lot of little classes each of which just has a static main method, then stop doing that. Write real Java classes instead. The tutorial is here:
    http://java.sun.com/docs/books/tutorial/java/index.html

  • Using an External Jar file

    I was hoping my intro programming class would be easy, as I've done some C++ before, but go figure, it's not.
    Although the language/concepts aren't to difficult to learn, it seems compiling programs is. For one program, I'm giving an external .jar file to use. I'm using crimson editor and I do have it setup with the jdk1.6.0. It compiles all my other programs besides this one (command line doesn't work either).
    Essentially, I've created a project, I have an instantiable class, and an application class. I can call the instantiable class in the app class and creating/modifying objects works just fine. Then I have a .jar file added to the project that came from the class (supposed to be used for I/O, don't know why we can't just use the standard java classes, but oh well). anyways, when I try to call the methods in the .jar file I get the following error:
    ---------- Capture Output ----------
    "C:\Program Files\Java\jdk1.6.0\bin\javac.exe" file.javafile.java:6: cannot find symbol
    symbol : variable externalJar
    location: class file
              int value = externalJar.getIntInput();
              ^
    After doing some searching, I found that it might be due to the classpath. So I set the classpath to the directory.. no go. Then I set the classpath to the externalJar.jar file and I get the follow error:
    ---------- Capture Output ----------
    "C:\Program Files\Java\jdk1.6.0\bin\javac.exe" -classpath C:\folder\externalJar.jar file.javaerror: error reading C:\folder\externalJar.jar; error in opening zip file
    I'm at a loss. It works when I use Eclipse and I can just add the external jar file, but I don't want to use eclipse, it's slow and bulky. Any other solutions to this problem? Thanks.
    E-Rod
    *names were changed for a reason.. i already know i'm not misspelling anything                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    The error about not being able to find the variable externalJar has nothing
    to do with the classpath. It's just that your code in file.java refers to this variable,
    but you have not declared it anywhere.
    Variables within a class, the names of classes and the names of .jar files
    which contain packages have nothing whatsoever to do with one another.
    If you are using a variable externalJar intending it to reference your external jar
    file in some way, then your file.java code is seriously wrong.
    (Also, classes and their associated source files should begin with an
    uppercase letter.)
    Regarding your attempt to specify the classpath when you invoke the
    compiler (always a good idea), I think you should also include the current
    directory (if that is where file.java is). Like this:"C:\Program Files\Java\jdk1.6.0\bin\javac.exe" -classpath C:\folder\externalJar.jar;. file.javaThe "error opening zip file" thing is odd. Make sure you are
    able to read it (permissions OK, no other process has it locked). And that
    it's not corrupt (Did you create it? If so, rebuild it. If not, aquire another copy.)
    Sorry for the generalities and guesswork, but without seeing any code and
    without knowing your directory structure or the contents of this externalJar.jar
    it's hard to do any more.

Maybe you are looking for