URL to resource in jar?

Hello
Does anyone know how to properly write an URL to point to a file within the Midlet's jar?
Say for instance that I have a file "music.mid" in the root of the jar-file of my Midlet suite, and want to access this via Manager.createPlayer(String url), how would I go about writing that url?

When creating a Player using createPlayer(InputStream is, String mime), all mp3's and most of the wavs does not work, no matter if they're placed inside the jar or on a memory stick. Those same audio files can be played without problems if placed on the memory stick and called via createPlayer(String url).
What I'm after is a way to write an URL that locates a file inside the jar. Something like "file:///c:/audio/music.mid", but for a resource in the actual jar and not on the phone memory.

Similar Messages

  • 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");

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

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

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

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

  • Classes+resources in JAR: have to add each single Jar file to CLASSPATH?

    Hello,
    For my application, I plan to easily embed plugins that can be added by the user by copying it into a subfolder "plugins".
    Now, I start my app from a shellscript and in order to load resources from within some of these Jars (e.g. using Class.getResourceAsStream() ), it only works if I explicitly add the specific Jar filename to the classpath from the shellscript.
    I read in a German Java book, that also just using folder names is enough, but it does not work for me:
    Works:
    $JAVA_HOME/bin/java -Djava.library.path="./lib" -classpath "./lib:./plugins/test.jar" test.AppFails:
    $JAVA_HOME/bin/java -Djava.library.path="./lib" -classpath "./lib:./plugins/" test.AppIs it really required to add Jars explicitly, so that e.g. my shellscript has to make a Jar listing of that folder in order to pass them as classpath files?
    Thanks and regards,
    Timo

    No, you don't have to do it that way. What you need
    to do is to have your progam create a URLClassLoader
    pointing to all the jars in the plugin directory.
    Then request your plugin classes from that, rather
    than Class.forName();
    You need to create an array of file URLs for the
    jars, use File.listFiles() and then File.toURL() on
    each ..jar you find.
    p.s. If you do it this way make sure your plugin
    classes are not on the classpath.
    Hmm. Cool. I had no idea. Thanks for correcting me.

  • 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

  • Relative URLs not working in JAR file once JAR is moved

    I've been loading images with the following:
    public static final ImageIcon anIcon = new ImageIcon("iconName.gif");
    This works fine when all the class files are in the same folder with the gifs. I then packaged the whole folder into a .jar file, moved the resulting .jar file to another directory, tried running it and none of the icons loaded. They are present in the .jar file, why doens't the relative URL still work? Is there simply another way to write the URL so that it knows to look in the .jar file?
    Thanks for help,
    Robert Douglass

    Is there simply another way to write the URL so that it knows to look in the .jar file?Once you put the class files along with your gif files in a jar, you have to access the gif file like this:
    import java.net.*;
    URL url=myClass.class.getResource("iconName.gif");
    ImageIcon anIcon = new ImageIcon(url);
    Where myClass is the name of your class file.
    V.V.

  • Image loading via URL with resources in packages

    And another newbie-question:
    When I want to access local media-files (for example images) in a subdirectory, I can use a url to get a local path/filename. For example:
    url = getClass().getResource("/path/image-name.gif");
    image = getToolkit().getImage(url);
    Now I have packaged my classes including the subdirs containing the images in a jar file.
    package.jar
    |
    -- subdir (with images)
    |
    -- a.class
    |
    -- b.class
    |
    -- x.class
    Now the access via url doesn't seem to work any longer. When I subclass "a" outside the package (with correct import-statements, of course) and the constructor of "a" tries to access the images in "subdir" (invoking super()), it cannot find it and an exception occurs.
    Is this correct, or does the error lie maybe somewhere else?
    I had the impression that a jar-archive can be accessed like a directory? Have I to access the images in another way to get them working inside a package? When the classes and images are not packaged, all works fine.
    I work with Sun One, btw., and do mount the jar-archive as a filesystem...
    Any advise?
    Thanks in advance.
    Xanathon

    Am I on the right way when using an URLClassLoader instead of getClass()?

  • Look for resources in jar

    I wrote an aplication and put it with all needed resources(images) in a jar file, but still when i start the executable jar the aplication looks for the images in the directory where the jar is and not in the jar. How can i make it looking for reources in the jar?

    Best approach is to use Class.getResource or Class.getResourceAsStream.
    You can read a jar file explicitly using java.util.jar.JarFile but getResource is easier.

  • Wsrp-requireRewrite for URLs in resource response ?

    I'm using Portal 10.1.4 serving WSRP content from a
    portlet producer running on 10.1.3.2 (JDev embedded OC4J).
    I want to use an AJAX resource request to serve a fragment of
    portlet markup containing further portlet and AJAX URLs.
    URL rewriting for full page portlet rendering requests works fine,
    but I can't get a resource request served with WSRP URL rewriting.
    Here is my approach ... a resource request is sent from a portlet page
    using a URL that was created in in a full portlet request.
    The flag 'wsrp-requireRewrite=true' is WSRP encoded as '__ora_rewrite=1'.
    The Portal server presumably intercepts the request and stores the value of this flag,
    then sends the raw resource request to the resource servlet on the portlet producer
    (i.e. markup generated through a servlet context, not a portlet context).
    The new markup fragment contains URLs embedded between 'wsrp_rewrite' tags.
    The Portal server should intercept the response and rewrite the URLs,
    but it swallows the whole thing, and an empty response is returned to the client.
    Is wsrp-requireRewrite=true supposed to work for resource requests ?
    Any ideas what could be wrong ?
    Mik

    The problem was MIME type.
    I had assumed Portal server would rewrite any text responses,
    but it does not rewrite 'text/xml' data, in fact it sends it to the bit bucket !
    So you need to force the response Content-Type in the resource provider.
    The only valid rewritable types seem to be:
    'text/plain', 'text/html' and variants like 'text/html+xml'.
    The rewritten URLs will not be XML-escaped
    i.e. '&' parameter separator will not be escaped to '&amp;amp;' .
    So when doing AJAX updates you have to explicitly escape the URLs
    and invoke an XML parser in client-side JavaScript,
    rather than relying on the implicit mechanisms within XmlHttpRequest.
    Mik

  • GIFs in package resources in JAR

    Hello all,
    I am deploying a java GUI with resource GIFS in a JAR.
    While I am developing in the IDE (Eclipse) everything works out fine: the resource GIFS are loaded from the package resources and are displayed in the GUI.
    Then I distribute a JAR using Ant: see manifest.mf at the end of the text.
    When I deploy the application now, no resource GIFS are displayed on the GUI. This behaviour changes non-deterministically.
    Error could be the packaging into JAR or display of the GUI?
    Thank you in advance,
    Gerrit Leder
    -----------------------------------------------------------------manifest.mf:
    Manifest-Version: 1.0
    Created-By: 1.5.0_09 (Sun Microsystems Inc.)
    Main-Class: vci/VciManagement
    Class-Path: .

    When I loaded the Image with getImage(...) I used checkImage(...):
    In the IDE the Result was 0.
    Then I loaded the Image with getImage(...) and used prepareImage(...) and then checkImage(....):
    In the IDE the result was 7 then 39.
    In the Jar the result was 64.
    What is the int code representing?
    Here is my code now:
    class ViewComponent extends JComponent
         private Image image;
         private int iResult;//checkImage: Result
         private boolean bResult;//prepareImage: Result
         protected void paintComponent( Graphics g )
              // Dimension size = this.getSize();
              this.setLocation(35,0);
              if (image.getWidth(this) <= 0 ){
                   this.setSize(16,16);
              } else {
                   this.setSize(image.getWidth( this), image.getHeight(this ) );
              if ( image != null ){
                   g.drawImage( image, 0, 0, this );
                   // System.out.println( "paintComponent: width = " + image.getWidth( this) + ", height = " + image.getHeight(this ) );
         public void setImage( String filename )
              image = Toolkit.getDefaultToolkit().getImage( filename );
              System.out.println( "filename >" + filename + "<: width = " + image.getWidth( this) + ", height = " + image.getHeight(this ) );
              if ( image != null )
                   bResult=prepareImage(image,
                        image.getWidth(this),
                        image.getHeight(this),
                        this);
                   iResult=checkImage(image,
                        image.getWidth(this),
                        image.getHeight(this),
                        this);
              System.out.println("BEFORE repaint(), checkImage Result: " + Integer.toString(iResult));
                   repaint();
                   iResult=checkImage(image,
                        image.getWidth(this),
                        image.getHeight(this),
                        this);
              System.out.println("AFTER repaint(), checkImage Result: " + Integer.toString(iResult));
    }

  • Localization of app resources in jar

    Hi,
    I got a problem localizing a Web Start App.
    I translated the resources in the property files like javax\swing\plaf\basic\resources\basic.properties as usual to basic_de.properties to support the german local.
    All work fine launching the app from command line.
    Then I added the new resource property file to my application jar.
    But launching the app with Web Start my localized properties in the jar seems to be ignored. I checked the default local in the app (DE_de) but the texts in the Swing dialog now appear again in english.
    Any ideas how I can get the translated resource to work?
    Thanks in advance for any information.
    Regards
    Martin Schloeter

    one possible guess is
    ClassLoader a has access to swing classes
    ClassLoader b has access to your app classes, and has a has its parent.
    swing classes loaded using b are in fact loaded by a. Now, those classes search for localized resources, they do so using their classloader, that is a. For a, no german localized file exist even though b would have found one.
    I do not know if WebStart plays more or less with class loaders, but the exemple I gave can reproduce your problem easily. You did not play for sure with dynamic class loading while running your command line tests.

  • 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

Maybe you are looking for

  • My apple tv is showing an image to plug into i tunes

    My apple tv is sayong to plug into ituens.... and still isnt working

  • Apple TV & iPod Touch

    Hello All, I am currently using an iPod Touch, and want to get an apple TV. I have 1 question before buying: I LOVE to watch podcasts. I am wondering if will be able to SYNC both of my devices to iTunes. For example. if I have 3 episodes of CommandN

  • Dreamweaver - Button Redirect To Web or Mobile Depending On Device

    In Dreamweaver, I have four buttons linking to various social media sites. (Facebook, Instagram, LinkedIn and YouTube)  I would like to script the buttons so that the browser will redirect to either the web-based version of the site or link to the mo

  • Displaying text in item continuously

    Hello. Is it possible to show continuously moving text in some item in forms? It would be for help in some item. User can use form, if he doesn't understand something, he can look at the text, which would repeat from start to end. Maybe with some jav

  • Need Very Basic Instructions, Please!!

    Please excuse my total ignorance, take pity. I am having trouble with apparently basic Reader usage. I have scoured Help and still have questions. Is there a Reader for Dummies type info. I have missed??