Resources inside JAR - problem

I have a strange problem with resources inside JARs.
I can't load any resource form a JAR file (for example a .property file or .png icon).
It's not a problem with my progams only. JDBC drivers doesn't work because they cannot find .properties files while they work well when, the driver JAR i uncompressed. It happens every time when some resouces are inside JAR library (classes are loade correctly). The same project runs well on my friend's computer while I've got an error on my computer.
I tried it on WinXP and Win2003 Server - the same. My java version 1.5.0_06-b05 (but I had the same problem with older versions).
I figured out that I can find a file inside a JAR, open a stream, load data and everything is OK but data is always 0bytes length. For example using:
ImageIcon myImageIcon = new ImageIcon(getClass().getResource(pathandfilename));
I get empty ImageIcons without any error.
Can anyone help me. Maybe I should find something somwhere in java configuration.
Message was edited by:
peper

But can anyone tell me why my servlet can not access the
contents inside a jar file?? Any suggestions please?
Thanks.Without seeing your code, it is likely that you are trying to use file names (like /some/path/yourFileName.ext), not resource names (loadable from the class loader) like /yourFileName.ext.
Example:
Instead of:
FileInputStream stream = new FileInputStream("/some/path/yourFileName.ext");
do this:
InputStream stream = getClass().getResourceAsStream("/yourFileName.ext");
There are other API's which take either a string file name or a URL. You want to go the URL way, where the URL is taken from the classpath as:
URL url = getClass().getResource("/yourFileName.ext");

Similar Messages

  • Loading resources from jar - problem

    I've got a problem when loading resources from jar.
    My code:
    package game.player;
    import javax.swing.ImageIcon;
    import java.awt.Image;
    import game.map.Map;
    import game.map.MapReader;
    import game.emptyclass.EmptyClass;
    import java.net.URL;
    public class Data
        ClassLoader cl = EmptyClass.class.getClassLoader();
        Image image1 = new ImageIcon(cl.getResource("data/sprites/man6.png")).getImage();
        Image image2 = new ImageIcon(cl.getResource("data/sprites/man5.png")).getImage();
        Image image3 = new ImageIcon(cl.getResource("data/sprites/man4.png")).getImage();
        Image image4 = new ImageIcon(cl.getResource("data/sprites/man3.png")).getImage();
        Image image5 = new ImageIcon(cl.getResource("data/sprites/man2.png")).getImage();
        Image image6 = new ImageIcon(cl.getResource("data/sprites/man1.png")).getImage();
        public Image tile1 = new ImageIcon(cl.getResource("data/maps/test/tile1.png")).getImage();
        public Image bg = new ImageIcon(cl.getResource("data/maps/default/bg.png")).getImage();
        public Map map = new MapReader(cl.getResource("data/maps/test/test.map").getPath()).getMap();
        public int getImageWidth()
            return image1.getWidth(null);
        public int getImageHeight()
            return image1.getHeight(null);
    }I get a NullPointerException.
    Thanks in advance!

    Hi ,
    getResource() method argument is not begin with the
    character '/' , ex.
    Image image1 = new
    ImageIcon(cl.getResource("/data/sprites/man6.png")).ge
    tImage();
    I thought of that, but it's not applicable here because getResource is being called on the ClassLoader, not the Class.

  • File Not Found inside jar

    Hi All,
    Im using applet to access a wav file which is located in the jar file, 1st of all im compiling the applet class, making a jar file(which has the welcome.jar in it) and signing the jar file and then archiving the jar file in the HTML code. following is the code used in the java applet file.
                    URL pathShell = null;
         Object dummy = new Object(){
                                 public String toString() { return super.toString(); }
         ClassLoader cl = dummy.getClass().getClassLoader();
         pathShell  = cl.getResource("welcome.wav");
         String wavFile = pathShell.toString();
         System.out.println("path  --- "+pathShell);
         System.out.println("String -- "+wavFile);
         RandomAccessFile rcs = new RandomAccessFile(wavFile,"rw");Exception messages is as follows,
                   path  --- jar:http://localhost/slider.jar!/welcome.wav
                   String -- jar:http://localhost/slider.jar!/welcome.wav
                    java.io.FileNotFoundException: jar:http:\localhost\slider.jar!\welcome.wav (The filename, directory name, or volume label syntax is incorrect)
         at java.io.RandomAccessFile.open(Native Method)
         at java.io.RandomAccessFile.<init>(Unknown Source)
         at java.io.RandomAccessFile.<init>(Unknown Source)
         at AudioPlay.<init>(AudioPlay.java:40)
         at SliderDemo.startAudio(SliderDemo.java:231)
         at SliderDemo.access$000(SliderDemo.java:17)
         at SliderDemo$5.actionPerformed(SliderDemo.java:144)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)

    b.m.kraju wrote:
    Hi All,
    Im using applet to access a wav file which is located in the jar file, 1st of all im compiling the applet class, making a jar file(which has the welcome.jar in it) and signing the jar file and then archiving the jar file in the HTML code. following is the code used in the java applet file.You can't open a resource inside a jar file as a RandomAccessFile or any other form of File.

  • Can't get file from resource in jar.

    hi,
    I'm using the folowing mechanism to get a configuration file from my classes jar file.
    URL configUrl = Config.class.getResource("/resources/"+fileName);
    File ressourceFile = new File(configUrl.toURI());while this is working perfectly when i run my app in stand-alone it fails in JavaWebStart. it gives me the folowing error :
    java.lang.IllegalArgumentException: URI is not hierarchical
         at java.io.File.<init>(Unknown Source)
         at line 2 aboveafter some investigation it seems that the first line doesn't return a valid URL. I'm getting something like :
    jar:file:C:/Documents%20and%20Settings/Patrice/Application%20Data/Sun/Java/Deployment/cache/javaws/http/Dfiona/P80/RMface2face.jar!/resources/system.propertiesthe problem (I think) lies in the URL protocol : jar:file:C:/...
    when I run the same lines in stand-alone I get :
    file:/E:/Project/.../classes/resources/system.propertieswhich is just what I want.
    Is there something I am doing wrong?
    thanx,
    Patrice.

    ok thanx.
    in the end I copy the file locally with :
    try{
        InputStream input = Config.class.getResourceAsStream("/resources/"+fileName);
        OutputStream output = new FileOutputStream(userConfigFile);
        byte[] temp = new byte[128];
        while(input.available()>0){
            int nb = input.read(temp);
            output.write(temp,0,nb);
        input.close();
        output.close();
    } catch (IOException e){
    }it works perfectly.
    thx.

  • Classnotfoundexception eventhough the class is inside jar

    Hi guys,
    I encountered weird problem where sometimes it throws classnotfoundexception eventhough the class is inside jar. I terminate the program and start it again then it works fine. I compiled the jar using ant
         <target name="compile" depends="clean" description="">
               <echo message="using java version    : ${java.version}"/>
               <echo message="using ant.java.version: ${ant.java.version}" />          
                 <javac srcdir="${src.dir}"
                        destdir="${build.dir}"
                        debug="on"
                        source="1.5"
                              excludes="com/csg/cs/mud/junit/*"
                 />
                <jar destfile="${mmd.jar}"
                     basedir="${build.dir}"
                     excludes="org/css/cs/mmd/juni*,org/css/cs/mmd/utility/MDDClient.class"
                />          
         </target> it shows :
    *[echo] using java version : 1.5.0_04*
    *[echo] using ant.java.version: 1.5*
    and I deployed this jar to sun solaris (SunOS sg123-456 5.8 Generic_117350-44 sun4u sparc SUNW,Ultra-80) and sun solaris box is using jre1.5.0_06.
    Appreciate any advice please. thanks in advance!
    Cheers,
    Mark
    Edited by: kmthien on Aug 2, 2010 3:05 AM

    Is it public?
    Is it spelt correctly, and the same, in the jar file and the code?
    Is it in its correct package in the jar file?
    Why are you excluding a class from the jar file?

  • Specify Main-Class to /bin folder inside Jar?

    I'd like to set the Main-Class of my runnable jar to use a class inside /bin INSIDE the jar
    this is because one of my packages's first folder is /gl and there is a /gl folder containing resources inside my jar's root dir... want to seperate those.
    Thanks!
    IE:
    Main-Class:bin/package.package.classname
    doesn't work, even if my classes are all inside bin.

    Make two jars, one for code, one for resources. Name the resource jar in the Class-Path of the first jar's manifest.
    The bin trick would not work.

  • How to edit a text file inside jar

    Hi all;
    I have a code that created text file and put this file to other jar archive.
    How can I edit this text file inside jar, add string to this file ?
    Thanks,

    Unpack the jar, edit the file, repack the jar.

  • Finding total number of class files present inside jar

    Is there any way to find the total numbef of class files present inside jar?
    Any link will be helpful.

    http://java.sun.com/j2se/1.4.2/docs/api/java/util/jar/JarFile.html#entries()
    You'll have to search through it.

  • How can I obtain the resources in jar?

    How can I obtain the resources in jar if the class that to want this resource is static?
    I don't succeed use like:
    getClass().getResourceAsStream("/" + name)
    because my class is static.
    Thaks

    You could do this
    new Object().getClass().getResourceAsStream("/" + name)
    or
    Object.class.getResourceAsStream("/" + name)

  • Acess DB inside jar

    Hai everyone,
    I developed a swing application which uses MS Access ,database.
    I packaged the application as a jar file. I also included the
    database inside the jar. But it is unable to connect to the
    database when the database is inside the jar. If database is ouside
    the jar, the application works fine. I used the following code for the database
    connectivity .
    Is it wrong to pack a database inside jar ?
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String dbPath = getClass().getResource("Test.mdb").getPath();
    dbPath = dbPath.substring(dbPath.indexOf("/")+1);
    String connectionString =
    "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + dbPath;
    System.out.println(dbPath);
    con = DriverManager.getConnection(connectionString);
    stmt = con.createStatement();

    Standard java cannot use a jar that is within another jar. You could write your own classloader, or look at a product named "onejar".
    Here is a tutorial that shows you how to package a NetBeans project so it can be executed outside of NB.
    http://www.netbeans.org/kb/articles/javase-deploy.html

  • Problems accessing resources in JAR Files

    Hi all,
    i'm using a third party software which isb trying to access a configuration file (xml file) residing inside its jar files.
    Without Webstart there are now problems, when deploying the software with Webstart, the resources could not be found.
    The software installs an streamhandler which handles all access to its resources.
    When this handler is instantiated, a Classloader is provided via Thread.currentThread()..getContextClassLoader().
    As i can see this classloader (and only this-) instance is used when resources are acessed.
    The classloader instance seems to me to be the correct one of type ...JNLPClassLoader.
    As i figured out the classloader is able to acess the resource In the Moment when the Handler is instantiated.
    But later in the code (inside of the Handler) any call of getResource() with identical parameter for the resource name fails.
    The classloader instance is the same as in the previous calls (which i have added for debug).
    The Handler class resides in a different jar file as the resource, but i have also tried to put them in one jar file achieving the same result.
    Has anyone an idea what is going wrong ?
    The application has "all-permissions" granted, but suprisingly i'm receiving an security exception when trying to call Class.getProtectactionDomain() inside of the Handler class.
    Could it be a security problem ?
    Thank you.
    Andrej
    Message was edited by:
    a.rippich
    Message was edited by:
    a.rippich

    Dear PCR Barry,
    I am afraid that I must agree with my colleague Kostas, who replied to your first teststand post. These are very tricky, indepth issues, and will require quite significant investigation. Furthermore, it will be very difficult for us to answer via the forums as we will likely need more input from yourself. As previously suggested, if you have a Standard Service Program (SSP), you can generate a Service Request by calling or e-mailing your local branch.
    Thank you for your time, and I am sorry that I have been unable to help you further,
    Best wishes,
    Rich R
    Applications Engineer
    National Instruments UK & Ireland

  • How to Read all files inside resource Folder inside Jar?

    I have a Jar file,,,, The program reads for resource files in the resource folder inside the Jar. I want my program to read all files inside this folder without knowing the names or the number of files in the folder.
    I am using this to make an Applet easy to be updated with spicific files. I just want to add a file inside the resource folder and Jar the program and automatically the program reads what ever is in there!!
    I used the File class to get all file names inside the resource folder. it works fine before Jarring the program. After I jar I recieve a URI not Herarichy Exception!!
    File fold=new java.io.File(getClass().getResource(folder).toURI());
    String[] files=fold.list();
    I hope the question is clear!!

    How to get the directory and jar file that you class resides in:
    // returns path and jarfile (ex: /home/mydir/my.jar)
    public String getJarfileName()
            // Get the location of the jar file and the jar file name
            java.net.URL outputURL = YourClass.class.getProtectionDomain().getCodeSource().getLocation();
            String outputString = outputURL.toString();
            String[] parseString;
            int index1 = outputString.indexOf(":");
            int index2 = outputString.lastIndexOf(":");
            if (index1!=index2) // Windows/DOS uses C: naming convention
               parseString = outputString.split("file:/");
            else
               parseString = outputString.split("file:");
            String jarFilename = parseString[1];
           return jarFilename;
    }If your my.jar was in /home/mydir, it will store "/home/mydir/my.jar" in jarFilename.
    note: getLocation returns "file:/C:/home/mydir/my.jar" for Windows/DOS and "file:/home/mydir/my.jar" for windows, thus why I look for the first and last index of the colon so I can correctly split the string.
    If you want to grab a file in the jar file and get an InputStream, do the following:
    import java.io.*;
    import java.util.Enumeration;
    // jar stuff
    import java.util.jar.*;
    import java.util.zip.ZipEntry;
    public class Jaris
       private JarFile jf;
       public Jaris(String jarFilename) throws Exception
           try
                           jf = new JarFile(jarFilename);
           catch (Exception e)
                jf=null;
                throw(e);
       public InputStream getInputStream(String matchString) throws Exception
           ZipEntry ze=null;
           try
              Enumeration resources = jf.entries();
              while ( resources.hasMoreElements() )
                 JarEntry je = (JarEntry) resources.nextElement();
                 // find a file that matches this string from anywhere in my jar file
                 if ( je.getName().matches(".*\\"+matchString) )
                    String filename=je.getName();
                    ze=jf.getEntry(filename);
          catch (Exception e)
             throw(e);
          InputStream is = jf.getInputStream(ze);
          return is;
       // for testing the Jaris methods
       public static void main(String[] args)
          try
               String jarFilename=getJarfileName();
               Jaris jis = new Jaris(jarFilename); // this is the string we got from the other method listed above
               InputStream is=jis.getInputStream("myfile.txt"); // can be used for xml, xsl, etc
          catch (Exception e)
             // this is just a test, so we'll ignore the exception
    }Happy coding! :)
    Doc

  • Accessing resource files inside Jar using Fat Jar Eclipse plugin

    Hi,
    I want to develop single JAR file that uses a set of other JAR libraries. I am using Fat Jar Eclipse plugin. It works fine. However, I have problem to access resources files (i.e. rdf file) using relative path from my classes. Is there any idea how can I pack, set classpath and use relative path in order to make it works.
    Thanks
    Zoran

    I have solved this problem. The problem was in a way how I have trying to access it. It should be like:
    URL fileURL = this.getClass().getResource("resource/myFile.rdf");
    Zoran

  • Specifying a resource inside a jar to ServletContext.getResource

    Hi,
    I have a jar inside which there is a directory containing several DTDs. I want to use ServletContext.getResource() method to get the URI of this directory so that I can pass this URI to the DocumentBuilder.parse() method for parsing some data.
    I want to know the format for specifying this directory location. Thanks in advance.

    The only way I have been able to do this sort of thing was to put a class inside the JAR, put the JAR in WEB-INF/lib, then use your class's classloader to access the other files in the JAR. Here is an example:
    I have a simple class that goes like this:
    package luke.util.dummy;
    public class DummyClass {}I put this in a jar with XML files:
    JAR Top Directory
      -- luke/util/dummy/DummyClass.class
      -- xml/Important.xmlThen, in my code I use:
    URL xmlURL = luke.util.dummy.DummyClass.class.getClassLoader().getResource("xml/Important.xml");I haven't found another way to peek inside the JAR using the ServletContext :( Even though the API says:
    "This method allows the servlet container to make a resource available to servlets from any source. Resources can be located on a local or remote file system, in a database, or in a .war file."
    (a war being a type of JAR)
    i have not been able to use the method with a WAR.

  • Opening html files inside jar

    Hi,
    I'm making a program where i have a set of help files in the form of html and i would like to open them when the user clicks the "Help" button and I used this code at first
    try
         Desktop.getDesktop().browse(new URI("resources/html/help.html"));
    catch (Exception ex)
         JOptionPane.showMessageDialog(null, "Could not open help.html in default browser\n", "Error", JOptionPane.ERROR_MESSAGE);
    }However after I made the jar and tried to execute on another computer however, it wouldn't work and would display the error message. I was wondering if there was some way that I could open the help.html in their default browser, or maybe a frame if that works, from the jar and have my program still be platform independent?

    ok so i just realized that it doesn't make sense for a program outside the jar, like IE or Firefox, to be able to access and open a file inside of the jar. I am now looking for suggestions on how to work around this problem for my program to be able to have a simple help system located inside the jar that can be loaded during runtime.
    Thanks for your suggestions.

Maybe you are looking for

  • Green tint in imovie export

    iMovie turned our video green when we exported it. Not sure what caused this or how to fix it. You can see what it looks like below--sort of.  The *whole video* plays green, not just the green frames. The video is of a screen capture from a DELL usin

  • My startup page displays top half in old mode and bottom half in 4.0 . What can I do to get the top part to display properly?

    Instead of getting the drop-down menu that you click, I am getting the old horizontal line with File Edit View History Bookmarks Tools Help But the little home page icon is on the far right, and (I hope) the awesome bar is working properly. This happ

  • Dba_objects: ORA-00942: table or view does not exist

    I created a proc like: CREATE OR REPLACE PROCEDURE SEE_PROC (v_owner varchar2) as begin EXECUTE IMMEDIATE 'SELECT COUNT(*) from dba_objects WHERE OBJECT_TYPE = :1 AND OWNER = :2' USING 'PROCEDURE', v_owner; end; for a dba user, say appadmin, and atte

  • IOS Numbers - How do I show an number as a duration?

    Probably a simple question but here's my issue. 12km at 11kmph = 1.09 hours - how do I display this as a duration in ios numbers. Tried changing the cell format to duration, that doesn't work. It changes very breifly to duration and then immediateloy

  • Scilab

    Dear Community, after installing the upgrade to Labview 8.5.1, Labview crashes when i try to open a vi, which contains Scilab Script Nodes or if i try to create a new Scilab Script node in an empty VI. I've even installed the SciLab Gateway again and