How to retrieve resources from a jar file ?

Hello,
Currently, I have application classes in a jar file, and all other resources (pictures, properties, and so forth..) in my windows folder. I do not have any problem for using them such way. For example to set an icon to a JFrame I have coded :
f.setIconImage("mypicture.jpg");To make installation easier, I'd like to put my picture into the jar file with the classes. Is it possible ? if so, how should I modify my code to make things work ? Should I specify a special path ?
Thanks for all
Gege

Thanks a lot, I'm going to try both ways.What both ways? Both replies are about the same thing -- using the classpath to find resources.
The question now is what about if there is the same file
name in the jar file and also in the directory ? Is
there a search hierarchy ?It will find the first one it encounters in the classpath. You shouldn't have 2 resources with the same name in the classpath -- that's just like having two classes with the same package and class name.

Similar Messages

  • How to use methods from a JAR file inside my springcontext (Oracle fusion 12c) class file?

    Dear Friends,
    I have a jar file, which has executed classes and methods in it. I want to make use of these methods inside my springcontext piece of code.
    Can someone please share an example  of how to write spingcontext code which is accessing classes/methods from  JAR files along with the any setup?
    Thanks,

    I have found the answer... as described in:
    http://java.sun.com/javase/6/docs/technotes/guides/lang/resources.html
    the problem was that the properties are loaded with the getResource & getResourceAsStream methods and I didn't know that one. I thought that is was loaded through findClass because I saw the property files trying to be loaded through findClass.
    The truth is that it tries to load with the getRessources methods and if it fails tries with the findClass/loadClass.
    To Fix the problem, I have simply overriden the getRessourceAsStream to do my magic and that was it.
    Thanks

  • How to retrieve IndividualStrings from a txt file using String Tokenizer.

    hello can any one help me to retrieve the individual strings from a txt file using string tokenizer or some thing like that.
    the data in my txt file looks like this way.
    Data1;
    abc; cder; efu; frg;
    abc1; cder2; efu3; frg4;
    Data2
    sdfabc; sdfcder; hvhefu; fgfrg;
    uhfhabc; gffjcder; yugefu; hhfufrg;
    Data3
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    i need to read the data as an individual strings and i need to pass those values to diffarent labels,the dat in Data3 i have to read those values and add to an table datamodel as 6 columns and rows depends on the data.
    i try to retrieve data using buffered reader and inputstream reader,but only the way i am retrieving data as an big string of entire line ,i tried with stringtokenizer but some how i was failed to retrive the data in a way i want,any help would be appreciated.
    Regards,

    Hmmm... looks like the file format isn't even very consistent... why the semicolon after Data1 but not after Data2 or Data3??
    Your algorithm is reading character-by-character, and most of the time it's easier to let a StringTokenizer or StreamTokenizer do the work of lexical analysis and let you focus on the parsing.
    I am also going to assume your format is very rigid. E.g. section Data1 will ALWAYS come before section Data2, which will come before section Data3, etc... and you might even make the assumption there can never be a Data4, 5, 6, etc... (this is why its nice to have some exact specification, like a grammar, so you know exactly what is and is not allowed.) I will also assume that the section names will always be the same, namely "DataX" where X is a decimal digit.
    I tend to like to use StreamTokenizer for this sort of thing, but the additional power and flexibility it gives comes at the price of a steeper learning curve (and it's a little buggy too). So I will ignore this class and focus on StringTokenizer.
    I would suggest something like this general framework:
    //make a BufferedReader up here...
    do
      String line = myBufferedReader.readLine();
      if (line!=null && line.trim().length()>0)
        line = line.trim();
        //do some processing on the line
    while (line!=null);So what processing to do inside the if statement?
    Well, you can recognize the DataX lines easily enough - just do something like a line.startsWith("Data") and check that the last char is a digit... you can even ignore the digit if you know the sections come in a certain order (simplifying assumptions can simplify the code).
    Once you figure out which section you're in, you can parse the succeeding lines appropriately. You might instantiate a StringTokenizer, i.e. StringTokenizer strtok = new StringTokenizer(line, ";, "); and then read out the tokens into some Collection, based on the section #. E.g.
    strtok = new StringTokenizer(line, ";, ");
    if (sectionNo==0)
      //read the tokens into the Labels1 collection
    else if (sectionNo==1)
      //read the tokens into the Labels2 collection
    else //sectionNo must be 2
      //create a new line in your table model and populate it with the token values...
    }I don't think the delimiters are necessary if you are using end-of-line's as delimiters (which is implicit in the fact that you are reading the text out line-by-line). So the original file format you listed looks fine (except you might want to get rid of that rogue semicolon).
    Good luck.

  • How to retrieve data from an Excel file which is located on server

    hi everybody,
                    I am using SAP NWDS 2004s .     
                I have done an application on how to export the table data into an Excel .
    Now i want to get the data from an Excel file which is located in server and display that data which is in excel in a View for example a Sample view in Webdynpro  .
    In Sample view i took a uielement textview to display the data ....   
    can any one help how to procced further
    Thanks in advance
    Madhavi

    Options to read Excel data to WebDynpro context
    Reading Excel Sheet from Java without using any Framework
    Reading Multiple Sheets of Excel Sheet from Java
    Few Threads
    How to Display the content of Excel file into Webdynpro Table
    Is it possible to upload data from excel file(.xls)
    Re: How to export the data as integer into excel sheet?
    regards
       Vinod

  • Photoshop album starter edition 3.2  how to retrieve photos from obsolete locked file?

    photoshop album starter edition 3.2   how to retri
    eve photos from obsolete locked file?

    Try in that product's forum
    http://forums.adobe.com/community/ps_album_starter

  • How To Load Sound From Inside jar File?

    Hello There
    i've made a jar file that contains Images&Pictures But I Can't Use Them
    So I Used For Loading Images
      URL url = this.getClass().getResource("image.jpg");
             setIconImage(new ImageIcon(url).getImage());and for loading sound when i use
      URL url = this.getClass().getResource("Bond2.wav");         
           AudioInputStream stream = AudioSystem.getAudioInputStream(new File(url));there's an error That The file Constructor doesn't take url
    how can i fix it?

    First_knight wrote:
    and for loading sound when i use
      URL url = this.getClass().getResource("Bond2.wav");         
    AudioInputStream stream = AudioSystem.getAudioInputStream(new File(url));there's an error That The file Constructor doesn't take url
    how can i fix it?Remove the "new File()". There is a getAudioInputStream() method that takes a URL.
    AudioInputStream in = AudioSystem.getAudioInputStream(url);

  • 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

  • How to call a function from a JAR file

    Hi ALL,
    I am trying to call a Public function from a JAR file from my JAVA
    file. Can you please provide an example or suggest a good resource?
    Basically my java file Test.Java should call a function called 'export_a_doc' from a JAR file Export.jar. How do I refer this in my Java file and call 'export_a_doc'?
    Thanx

    Hi,
    HERE IS MY JAVA FILE
    // We need this for Starting our Export Process
    import com.newexport.Myclass;
    public class MyTest {
         // Our function to Start Export
         protected static void test(String[] args) {
         System.out.println("Starting. \n---------------------");
         Myclass p = new Myclass();
         try {
    p.Start_Export(args);
    System.out.println("Finished. \n---------------------");
         } catch(Exception e) {
    e.printStackTrace();
         public static void main(String[] args) {
         test(args);
    HERE IS THE BATCH FILE TO BUILD AND RUN
    cd \JNI\Srcs
    echo "-------------"
    c:\JBuilder7\jdk1.3.1\bin\javac -classpath C:\JNI\Export.jar MyTest.java
    echo "-------------"
    \JBuilder7\jdk1.3.1\bin\java.exe -classpath c:\JNI\Export.jar MyTest
    The Export.jar uses other jar files
    Raj

  • How to retrieve value from xml file

    hi all,
    can somebody pls tell me how to retrieve value from xml file using SAXParser.
    I want to retrieve value of only one tag and have to perform some validation with that value.
    it's urgent .
    pls help me out
    thnx in adv.
    ritu

    hi shanu,
    the pbm is solved, now i m able to access XXX no. in action class & i m able to validate it. The only thing which i want to know is it ok to declare static ArrayList as i have done in this code. i mean will it affect the performance or functionality of the system.
    pls have a look at the following code snippet.
    public class XMLValidator {
    static ArrayList strXXX = new ArrayList();
    public void validate(){
    factory.setValidating(true);
    parser = factory.newSAXParser();
    //all factory code is here only
    parser.parse(xmlURI, new XMLErrorHandler());     
    public void setXXX(String pstrXXX){          
    strUpn.add(pstrXXX);
    public ArrayList getXXX(){
    return strXXX;
    class XMLErrorHandler extends DefaultHandler {
    String tagName = "";
    String tagValue = "";
    String applicationRefNo = "";
    String XXXValue ="";
    String XXXNo = "";          
    XMLValidator objXmlValidator = new XMLValidator();
    public void startElement(String uri, String name, String qName, Attributes atts) {
    tagName = qName;
    public void characters(char ch[], int start, int length) {
    if ("Reference".equals(tagName)) {
    tagValue = new String(ch, start, length).trim();
    if (tagValue.length() > 0) {
    RefNo = new String(ch, start, length);
    if ("XXX".equals(tagName)) {
    XXXValue = new String(ch, start, length).trim();
    if (XXXValue.length() > 0) {
    XXXNo = new String(ch, start, length);
    public void endElement(String uri, String localName, String qName) throws SAXException {                    
    if(qName.equalsIgnoreCase("XXX")) {     
    objXmlValidator.setXXX(XXXNo);
    thnx & Regards,
    ritu

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

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

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

  • Loading Resources from a .JAR

    I've read through this forum and searched java.sun.com and have found nothing to solve my problem, although I see many other people are having the same problem.
    I wrote a small application that needs to load a text file and images. When I just compile everything and then run it, all is well, my text file is found and my images are displayed. Now the problem is when I package everything into a .JAR file, suddenly my magic stops. Here is the directory structure
    - State.class
    FiftyStatesGame.class
    FlagPanel.class
    StatsPanel.class
    StatePanel.class
    states.txt
    /images
    /flags
    a bunch of .gif images (50 total)
    /states
    a bunch of .gif images (50 total)
    I create my archive with the following command
    jar cvf FiftyStates.jar *
    and all seems well, I've even changed the extension to .zip to ensure that the images and text file is inside the jar
    Now when I try to run the program using
    java -cp FiftyStates.jar FiftyStatesGame
    the program starts but I get a NullPointerException and my pictures don't load. :-(
    I've read in the forum about using
    URL imageURL = ClassLoader.getSystemResource(<path to image>);
    Image logo = Toolkit.getDefaultToolkit().getImage(imageURL);
    and I tried this and once again, it works when not in jar form, but as soon as the application is JARed, I encounter the same problems.
    Can anyone give me the answer to this crazy problem?
    and I guess I should go one step further and ask, if I want to give this program to a friend with the JRE installed on a windows machine, what command should I put in my batch file to run this program on his machine?
    javaw -cp FiftyStates.jar FiftyStatesGame
    Thanks for any help and advice

    Hi,
    Getting the image
    =================
    It seems to me you can't be too far away from resolving your problem.
    I've never actually tried to get an image from a jar file, so I'm guessing that this may not work for you, but I have unzipped a zip file contained within an executable jar.
    What I did was this:
        private ZipInputStream findInstallationFile() {
            ClassLoader classLoader;
            URL url;
            ZipInputStream zipInputStream = null;
            InputStream inputStream;
            classLoader = getClass().getClassLoader();
            url = classLoader.getResource(ZIP_RESOURCE_NAME);
            if (url != null) {
                try {
                    inputStream = url.openStream();
                    zipInputStream = new ZipInputStream(inputStream);
                } catch (IOException ioe) {
                    ioe.printStackTrace();
            } else {
                System.err.println("Failed to find resource: " + ZIP_RESOURCE_NAME);
            return zipInputStream;
        }The good thing about this is that you can see whether or not the resource was found in the jar file. If the returned URL is null, then the resource isn't there.
    Once you have the InputStream, you can just read the entire contents and do what you like with them.
    Executable jars
    ===============
    You can make it easier to run a jar file by including a manifest file. This is just a text file which should be in the META-INF directory in your jar file. The manifest file itself should be called Manifest.mf.
    The contents of the Manifest should be:
    Manifest-Version: 1.0
    Main-Class: FiftyStatesGame
    This assumes that your main class is FiftyStatesGame which is in the default package (tut, tut!).
    Hope this helps!
    Rhys

  • How to create and use library JAR files with command-line tools?

    Development Tools -> General Questions:
    I am trying to figure out how to put utility classes into JAR files and then compile and run applications against those JAR files using the command-line javac, jar, and java tools. I am using jdk1.7.0_17 on Debian GNU/Linux 6.0.7.
    I have posted a simple example with one utility class, one console application class, and a Makefile:
    http://holgerdanske.com/users/dpchrist/java/examples/jar-20130520-2134.tar.gz
    Here is a console session:
    2013-05-20 21:39:01 dpchrist@desktop ~/sandbox/java/jar
    $ cat src/com/example/util/Hello.java
    package com.example.util;
    public class Hello {
        public static void hello(String arg) {
         System.out.println("hello, " + arg);
    2013-05-20 21:39:12 dpchrist@desktop ~/sandbox/java/jar
    $ cat src/com/example/hello/HelloConsole.java
    package com.example.hello;
    import static com.example.util.Hello.hello;
    public class HelloConsole {
        public static void main(String [] args) {
         hello("world!");
    2013-05-20 21:39:21 dpchrist@desktop ~/sandbox/java/jar
    $ make
    rm -f hello
    find . -name '*.class' -delete
    javac src/com/example/util/Hello.java
    javac -cp src src/com/example/hello/HelloConsole.java
    echo "java -cp src com.example.hello.HelloConsole" > hello
    chmod +x hello
    2013-05-20 21:39:28 dpchrist@desktop ~/sandbox/java/jar
    $ ./hello
    hello, world!I believe I am looking for:
    1. Command-line invocation of "jar" to put the utility class bytecode file (Hello.class) into a JAR?
    2. Command-line invocation of "javac" to compile the application (HelloConsole.java) against the JAR file?
    3. Command-line invocation of "java" to run the application (HelloConsole.class) against the JAR file?
    I already know how t compile the utility class file.
    Any suggestions?
    TIA,
    David

    I finally figured it out:
    1. All name spaces must match -- identifiers, packages, file system, JAR contents, etc..
    2. Tools must be invoked from specific working directories with specific option arguments, all according to the project name space.
    My key discovery was that if the code says
    import com.example.util.Hello;then the JAR must contain
    com/example/util/Hello.classand I must invoke the compiler and interpreter with an -classpath argument that is the full path to the JAR file
    -classpath ext/com/example/util.jarThe code is here:
    http://holgerdanske.com/users/dpchrist/java/examples/jar-20130525-1301.tar.gz
    Here is a console session that demonstrates building and running the code two ways:
    1. Compiling the utility class into bytecode, compiling the application class against the utility bytecode, and running the application bytecode against the utility bytecode.
    2. Putting the (previously compiled) utility bytecode into a JAR and running the application bytecode against the JAR. (Note that recompiling the application against the JAR was unnecessary.)
    (If you don't know Make, understand that the working directory is reset to the initial working directory prior to each and every command issued by Make):
    2013-05-25 14:02:47 dpchrist@desktop ~/sandbox/java/jar
    $ cat apps/com/example/hello/Console.java
    package com.example.hello;
    import com.example.util.Hello;
    public class Console {
        public static void main(String [] args) {
         Hello.hello("world!");
    2013-05-25 14:02:55 dpchrist@desktop ~/sandbox/java/jar
    $ cat libs/com/example/util/Hello.java
    package com.example.util;
    public class Hello {
        public static void hello(String arg) {
         System.out.println("hello, " + arg);
    2013-05-25 14:03:03 dpchrist@desktop ~/sandbox/java/jar
    $ make
    rm -rf bin ext obj
    mkdir obj
    cd libs; javac -d ../obj com/example/util/Hello.java
    mkdir bin
    cd apps; javac -d ../bin -cp ../obj com/example/hello/Console.java
    cd bin; java -cp .:../obj com.example.hello.Console
    hello, world!
    mkdir -p ext/com/example
    cd obj; jar cvf ../ext/com/example/util.jar com/example/util/Hello.class
    added manifest
    adding: com/example/util/Hello.class(in = 566) (out= 357)(deflated 36%)
    cd bin; java -cp .:../ext/com/example/util.jar com.example.hello.Console
    hello, world!
    2013-05-25 14:03:11 dpchrist@desktop ~/sandbox/java/jar
    $ tree -I CVS .
    |-- Makefile
    |-- apps
    |   `-- com
    |       `-- example
    |           `-- hello
    |               `-- Console.java
    |-- bin
    |   `-- com
    |       `-- example
    |           `-- hello
    |               `-- Console.class
    |-- ext
    |   `-- com
    |       `-- example
    |           `-- util.jar
    |-- libs
    |   `-- com
    |       `-- example
    |           `-- util
    |               `-- Hello.java
    `-- obj
        `-- com
            `-- example
                `-- util
                    `-- Hello.class
    19 directories, 6 filesHTH,
    David

  • How to retrieve info from a MacOs Standard floppy?

    How can I retrieve information from a MacOs Standard formatted floppy disk on Snow Lion?
    I have this collection of old floppy disks that were formatted as MacOs Standard format back in the days. They do hold some files which I'd like to backup on a backup drive.
    But, Snow Lion does not read MacOs Standard formatted disks apparently.
    So, does anyone know how to retrieve information from MacOs Standard formatted floppy disks?
    Thank you!

    This what I see in ML with my old SmartDisk VST (model# FDUSB-M) floppy drive:
    Interesting observations:
    1. I was able to add and remove files to the disk.
    2. I was not able to erase the disk with Disk Utility. It returned an error.
    3. Disk Utility did not offer the HFS+ format option, only FAT32 and ExFAT.
    4. I could only find 1 floppy in my house so it could be partially defective.

Maybe you are looking for

  • Help is not working in Form Builder 6i

    Hi all, I'm using Forms builder 6i in Windows7 system. When i go to Help menu and click 'Form Builder Help Topics' a error message is coming. I've reinstalled it many times. In Windows XP system it's working fine. Why it's not working in Windows7? An

  • ZAP_AGE - Vendor Payment History with OI Sorted List

    Hi, I am suggesting this report to my client as Vendor ageing report. This report is calculating the overdue values from the document date of the vendor invoice, However, my client wants to calcuate the values from the Due date of the Invoice. Is the

  • Very basic initial configuration question.

    Hi. I replaced a Catalyst 2960G for a C2960X-24-L in a network where there are already five switches. I have no idea how to assign it an ip : is there anyone here willing to explain that in  very simple way ? I tried plug it in the existing network,

  • Music in the cloud

    How do you get purchased music from the cloud? It doesn't always show up.

  • Facetime will not connect after upgrading to OSX Yosemite

    I upgraded to Yosemite, I've been having connection issues with Facetime. Every time I attempt to call someone it always tells me that the user isn't available. I can connect to users when I use my iPad. Any suggestions?