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).

Similar Messages

  • 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

  • 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.......

  • 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

  • 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.

  • 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.

  • 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.

  • 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 do I store images in a jar file to be displayed on a jsp?

    Afternoon all,
    I have created a java component which accepts some parameters and returns a string. The returned string contains html tags to display a table in a webpage when rendered through a browser.
    I want to be able to add this component to any java web project to display my table. The problem is that I want to use images in my table to give the appearance of curved corners.
    How do I store images in my component and render to a webpage?
    Thanks in advance,
    Alex

    You won't be able to make the install of this library as simple as the installation of a jar file. You can't access the images directly in the jar.
    There are a few approaches you can take:
    1 - jar file + resources:
    Have the install as being a jar and a "resources" directory which you store all the images in. Thus the images become part of the web application/web site and are accessible. Probably need to allow an entry in web.xml to configure where/what this directory is called.
    2 - jar file only:
    Provide a servlet to access the images, which will load them from the jar file, using the ClassLoader.getResourceAsStream(). Requires declaration of a servlet in the web.xml file. Won't be as efficient as having the images on disk, but will keep them bundled in the jar file.
    you would generate code such as <img src="myImgServlet?img=.....">
    Cheers,
    evnafets

  • Problem parsing XML with schema when extracted from a jar file

    I am having a problem parsing XML with a schema, both of which are extracted from a jar file. I am using using ZipFile to get InputStream objects for the appropriate ZipEntry objects in the jar file. My XML is encrypted so I decrypt it to a temporary file. I am then attempting to parse the temporary file with the schema using DocumentBuilder.parse.
    I get the following exception:
    org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element '<root element name>'
    This was all working OK before I jarred everything (i.e. when I was using standalone files, rather than InputStreams retrieved from a jar).
    I have output the retrieved XML to a file and compared it with my original source and they are identical.
    I am baffled because the nature of the exception suggests that the schema has been read and parsed correctly but the XML file is not parsing against the schema.
    Any suggestions?
    The code is as follows:
      public void open(File input) throws IOException, CSLXMLException {
        InputStream schema = ZipFileHandler.getResourceAsStream("<jar file name>", "<schema resource name>");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
          factory.setNamespaceAware(true);
          factory.setValidating(true);
          factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
          factory.setAttribute(JAXP_SCHEMA_SOURCE, schema);
          builder = factory.newDocumentBuilder();
          builder.setErrorHandler(new CSLXMLParseHandler());
        } catch (Exception builderException) {
          throw new CSLXMLException("Error setting up SAX: " + builderException.toString());
        Document document = null;
        try {
          document = builder.parse(input);
        } catch (SAXException parseException) {
          throw new CSLXMLException(parseException.toString());
        }

    I was originally using getSystemResource, which worked fine until I jarred the application. The problem appears to be that resources returned from a jar file cannot be used in the same way as resources returned directly from the file system. You have to use the ZipFile class (or its JarFile subclass) to locate the ZipEntry in the jar file and then use ZipFile.getInputStream(ZipEntry) to convert this to an InputStream. I have seen example code where an InputStream is used for the JAXP_SCHEMA_SOURCE attribute but, for some reason, this did not work with the InputStream returned by ZipFile.getInputStream. Like you, I have also seen examples that use a URL but they appear to be URL's that point to a file not URL's that point to an entry in a jar file.
    Maybe there is another way around this but writing to a file works and I set use File.deleteOnExit() to ensure things are tidied afterwards.

  • Is it possible to load classes from a jar file

    Using ClassLoader is it possible to load the classes from a jar file?

    URL[] u = new URL[1] ;
    u[0] = new URL( "file://" + jarLocation + jarFileName + "/" );
    URLClassLoader jLoader = new URLClassLoader( u );
    Object clsName = jLoader.loadClass( clsList.elementAt(i).toString() ).newInstance();
    I get this error message.
    java.lang.ClassNotFoundException: ExceptionTestCase
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:297)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:253)
    // "file://" + fileLocation + fileName + "/" This works fine from a browser.
    Is there anything I am missing? Thanks for the reply.

  • 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

  • Executing an file.exe from a jar file?

    Does anyone know how to execute an *.exe file from jar file?
    I have two files that I want to execute in one java.class, Monview.exe and Moninit.exe. Both are stored in the same jar file as the class called link.class.
    This is my code to run one of the files from the hard drive
    String []cmd={"c:\\monview.exe"};
    try
    Process pr = Runtime.getRuntime().exec(cmd);
    StringBuffer buf = new StringBuffer();
    InputStream istr = pr.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(istr));
    String str;
    while ((str = br.readLine()) != null) {      
                             buf.append(str);
    try {       
    pr.waitFor();
    } catch (InterruptedException e) { }
         if (pr.exitValue() != 0) {      
         br.close();
    catch (IOException e){}
    It works when i place both .exe on the local host harddrive but when I place it in the jar file nothing happens. Could anyone help me please on why does this happen and how I can fix it? Or on how to get the link.class code to extract it from the jar file and place it on the system directory and delete it from the system directory, without it knowing where the jar file comes from?

    Hello,
    If I am not mistaken, by including the JAR file in the CLASSPATH (specifying the absolute path), or after the -classpath option after the java command (java -classpath jar_archive main_class), the system will find both files in the JAR archive.
    Hope this helps!

Maybe you are looking for