Accessing JARred resource file

Hi,
My app uses an XML file. How might I construct the java.io.File so that when I JAR the app, it can be executed from any where on my file system? Currently, I have to hardcode the File absolute path which is very limiting and undesirable.
e.g: private File configFile = new File("c:\dev\myproj\config\config.xml");
works, bit I wish to have the resource file bundled in to the JAR, so the path must be relative i.e accessible to the app, no matter where the JAR is executed from. How can I achieve this please?
thanks
Paul.

To find about more about a class, you can always look it up in the API: [http://java.sun.com/javase/6/docs/api/]
For example, here is the constructor in question:
[http://java.sun.com/javase/6/docs/api/java/io/InputStreamReader.html#InputStreamReader(java.io.InputStream,%20java.lang.String)]
Click on the [charset |http://java.sun.com/javase/6/docs/api/java/nio/charset/Charset.html] link for more information about that string.

Similar Messages

  • Cannot access local resource file

    When I run my application on browser these error comes, I have found to change right click on project>properties>flex build path>libary path> framework linkage to "Merge into code"not working,
    I have also changed right click on project> properties>Flex compiler> Additional compiler arguments - -locale en_US to some -network false still its not working
    and undid whatever change i made,
    Help!
    SecurityError: Error #2148: SWF file http://localhost/aamshare-debug/aamshare.swf cannot access local resource file:///C|/wamp/www/aamshare-debug/media/bse.png. Only local-with-filesystem and trusted local SWF files may access local resources.
        at flash.display::Loader/_load()
        at flash.display::Loader/load()
        at mx.controls::SWFLoader/loadContent()[C:\autobuild\3.2.0\frameworks\projects\framework\src \mx\controls\SWFLoader.as:1611]
        at mx.controls::SWFLoader/load()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\con trols\SWFLoader.as:1380]
        at mx.controls::SWFLoader/initializeHandler()[C:\autobuild\3.2.0\frameworks\projects\framewo rk\src\mx\controls\SWFLoader.as:1971]
        at flash.events::EventDispatcher/dispatchEventFunction()
        at flash.events::EventDispatcher/dispatchEvent()
        at mx.core::UIComponent/dispatchEvent()[C:\autobuild\3.2.0\frameworks\projects\framework\src \mx\core\UIComponent.as:9298]
        at mx.core::UIComponent/set processedDescriptors()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\UICom ponent.as:1217]
        at mx.core::UIComponent/initializationComplete()[C:\autobuild\3.2.0\frameworks\projects\fram ework\src\mx\core\UIComponent.as:5395]
        at mx.core::UIComponent/initialize()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx \core\UIComponent.as:5379]
        at mx.core::UIComponent/http://www.adobe.com/2006/flex/mx/internal::childAdded()[C:\autobuild\3.2.0\frameworks\pro jects\framework\src\mx\core\UIComponent.as:5267]
        at mx.core::Container/http://www.adobe.com/2006/flex/mx/internal::childAdded()[C:\autobuild\3.2.0\frameworks\pro jects\framework\src\mx\core\Container.as:3305]
        at mx.core::Container/addChildAt()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\c ore\Container.as:2217]
        at mx.core::Container/addChild()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\cor e\Container.as:2140]
        at mx.core::Container/createComponentFromDescriptor()[C:\autobuild\3.2.0\frameworks\projects \framework\src\mx\core\Container.as:3681]
        at mx.core::Container/createComponentsFromDescriptors()[C:\autobuild\3.2.0\frameworks\projec ts\framework\src\mx\core\Container.as:3493]
        at mx.containers::ViewStack/instantiateSelectedChild()[C:\autobuild\3.2.0\frameworks\project s\framework\src\mx\containers\ViewStack.as:1140]
        at mx.containers::ViewStack/commitProperties()[C:\autobuild\3.2.0\frameworks\projects\framew ork\src\mx\containers\ViewStack.as:664]
        at mx.core::UIComponent/validateProperties()[C:\autobuild\3.2.0\frameworks\projects\framewor k\src\mx\core\UIComponent.as:5807]
        at mx.managers::LayoutManager/validateProperties()[C:\autobuild\3.2.0\frameworks\projects\fr amework\src\mx\managers\LayoutManager.as:539]
        at mx.managers::LayoutManager/doPhasedInstantiation()[C:\autobuild\3.2.0\frameworks\projects \framework\src\mx\managers\LayoutManager.as:659]
        at Function/http://adobe.com/AS3/2006/builtin::apply()
        at mx.core::UIComponent/callLaterDispatcher2()[C:\autobuild\3.2.0\frameworks\projects\framew ork\src\mx\core\UIComponent.as:8628]
        at mx.core::UIComponent/callLaterDispatcher()[C:\autobuild\3.2.0\frameworks\projects\framewo rk\src\mx\core\UIComponent.as:8568]

    Since you are loading your swf over http, it will be placed in a remote sandbox and will not be able to access the local filesystem. You should load your png in the same way as your swf (ie. over http), or embed it into your application.

  • File.seperator fails accessing jar resource

    my code is like this:
    URL myURL = getClass().getResource("image" + System.getProperty("file.seperator") + imageName);
    It works perfectly when i run from my IDE. But when i package this into a JAR file, it fails with NullPointerException (it cant find the image in my JAR). When I look at what it is doing in the debugger, it seems to create the filename: "image%5c(imagename)" It uses %5c as a file seperator? escape code for "/" (windows environment) i presume??
    If i change my code to "image" + "/" + imageName it works perfect, but this is windows dependent and I dont want to do that.
    Has anyone come across this? what is a simple work around?

    It's not Windows-dependent. You are producing a URL
    there and they always, in all environments, use the /
    character to separate path elements. So yes, you DO
    want to do that.thank you. Why of course, it is a URL and URLs are always using "/".
    So I understand correctly ... if i reference actual FILES on my computer, i should STILL use System.getProperty(file.separator), though, right?

  • Accessing Jar resource issue (in Junit test)

    Hi,
    I have a package called my.test.example containing one class called Example1.class and a property file called MyProp.properties. I am trying to load the content of MyProp.properties with the following:
    static {
        Properties Configuration = new Properties();
        try {
           URL url = Example1.class.getResource("/MyProp.properties");
           Configuration.load(url.openStream());
        } catch (IOException ex) {
            LOG.severe("Cannot load MyProp.properties :\n" + ex.toString());
    }The url is systematically null. I have tried including the package name, to use '/' instead of '.', but it does not work. How should I proceed? I am looking for a solution that works wherever the .jar is installed. Is this possible?
    Thanks.
    P.S.: I am working under Vista and the static code is invoked in a Junit test. I don't know whether this has an impact on the issue (but I don't think so).

    OK. Solved the issue with:
    Configuration.load(Example1.class.getResourceAsStream("MyProp.properties"));I had to solve another 'hidden' bug in the code.

  • Accessing Resource file in a bundle from unit test case

    Hello All,
    Here is my problem . I have a plugin app that is loaded in of the host application. I have a resource plist file in the plugin. I access the resource using the api [[[NSBundle mainBundle[ bundleWithIdentifier:@"MyPluginIdentifier"] pathForResource@"Resource_Name" ofType:@"Resource_Type"]. This I get path of the resource file perfectily, but it fails when I do unit testing. I am using SenTest framework kit for unit testing. When I access the resource by using above api, I get null value. Since the running executable will be otest which is located at /Developer/Tools folder, So how to access my resource file in unit test. Should I need to hard code for the Path? Any inputs are highly appreciated.
    Thanks,
    Naveen

    So there is some important stuff realized by the UIKit UIApplicationMain function that has to be reproduced in the setup of the test.

  • Servlet -- Resource File

    I have a file Resource File that I want to open in a Servlet.
    The code in the servlet attempting to access the resource file.
    Properties objProperty = new Properties();
    objProperty.load(ClassLoader.getSystemResourceAsStream("jdbc.datasource"));
    String strSource = objProperty.getProperty("datasource.source");
    String strUsername = objProperty.getProperty("datasource.username", "");
    String strPassword = objProperty.getProperty("datasource.password", "");I get a null pointer exception. Where do I put this Resource File file in the .war directory structure? Do I have to set any other variables (classpath, etc...) and where?
    Thanks,
    DeltaCoder

    i assume it is a file called jdbc.datasource? try putting it into the root of the web-application.
    but you might want to consider using resource-references instead. the configuration depends on the application-server though. here's an example how to define resource-references for the jboss-server.: http://www.huihoo.com/jboss/online_manual/3.0/ch07s22.html
    hope this helps ;-)

  • 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

  • How to build a jar file so the program can access its resources folder?

    I have a java program written by someone else in which I have made a trivial change (I changed the background color). The jar file runs but it does not find one of the resources file.
    Here is the project folder's structure
    mainClass.txt (manifest text file)
    folder resources (includes file Java does not find: order.txt, a text file)
    folder CFPT ( includes .class files)
    folder cpl (includes .class files)
    folder results
    I tried
    jar cvmf mainClass.txt CFPT0.jar CFPT/*.class cpl/*.class resources results
    I get a lot of "adding: resources/..."
    including the one pertaining to the files which is later not found
    adding: resources/order.txt(in = 411) (out= 169)(deflated 58%)
    the code that chokes right now is the following,
    Object i = new Object();
    InputStream is = i.getClass().getResourceAsStream("/resources/" + resourceName);
    when I run java -jar CFPT0.jar the program runs
    but it soon gives an error, cannot find resourceName order.txt (is == null)
    I have Core Java Volume 1 page 498 but it does not help me figure out what I am doing wrong.
    Can somone help me build the jar file correctly so the program can find its resources?
    Is this a classpath issue? What do I need to do?

    My last mainClass.txt file content:
    Main-Class: CFPT.CFPTRunner
    Class-Path: ./resources ./results
    I also tried
    Class-Path: resources results
    Initially I only had the first line.
    I put back /resources in the java file as the / is necessary to indicate absolute path.
    Otherwise it looks relative to calling class.
    I tried adding the path on the second line of the manifest file per Wikipedia example
    http://en.wikipedia.org/wiki/Classpath
    I looked at
    http://java.sun.com/javase/6/docs/technotes/guides/lang/resources.html
    If you use the -sourcepath option, the compiler searches the indicated path for source files; otherwise the compiler searches the user class path both for class files and source files.
    http://java.sun.com/javase/6/docs/technotes/guides/lang/resources.html
    resources
    I took out the -d classes and compiled the .class files right with the java files in case that was the problem
    javac -classpath . CFPT/CFPTRunner.java
    jar cvmf mainClass.txt CFPT0.jar CFPT/*.class cpl/*.class resources results
    java -jar CFPT0.jar
    Still no go

  • Security restrictions , how to read access a txt file supplied in a jar

    I had written a simple application which uses file handling to display random line from a file on a swing window
    but I do not know how to give my web application permission to access a file
    when I set security permission to all, then error says the application cannot load because the code require unrestricted acess to system resources and is unsigned, I don't know how to get that certificate and I am only doing it for learning purposes.
    when I remove security permissions then it says
    access denied java.io.FilePermissions geekjoskes.txt readPlease help
    I locally signed the jar file, and give my jnlp fiel all permissions, worked fine in my system but when I access same file from local lan it sho errors ,
    please help, I have my txt file stored in my jar file with main class
    the whole jnlp file is
    <?xml version="1.0" encoding="utf-8"?>
    <!-- JNLP File for geek jokes -->     
    <jnlp spec="1.0+"
           codebase="http://localhost/javasoft/webstart/"
          href="geekjokes.jnlp">
       <information>
          <title>Geek Jokes</title>
          <vendor>Vaibhav Mishra</vendor>
          <description>Geeky jokes</description>
          <homepage href="http://scjpbeginner.blogspot.com"/>
          <description kind="short">shows random jokes</description>
          <offline-allowed/>
       </information>
       <resources>    
            <jar href="GeekJokes0.1.jar"/>  
         <j2se version="1.6+"
               href="http://java.sun.com/products/autodl/j2se"/>
         <icon href="geekjokes.gif"/>
       <icon kind="splash" href = "geekjokes.gif"/>
       </resources>
       <security>
          <all-permissions/>
       </security>
       <offline-allowed/>  
       <application-desc main-class="GeekJokes"/>
    </jnlp>Edited by: 76jsr on Aug 7, 2008 3:45 PM
    Edited by: 76jsr on Aug 7, 2008 3:49 PM

    >
    I am extremely thankful to you and finally my first little app is working thanks to you,
    here is it's link
    [http://profile.iiita.ac.in/IIT2006117/javasoft/webstart/geekjokes/geekjokes.jnlp|http://profile.iiita.ac.in/IIT2006117/javasoft/webstart/geekjokes/geekjokes.jnlp] >
    I am glad you got it working! But that launch file is still slightly invalid.
    Here is a corrected, and slightly optimized (you can leave the prefix off the href, if it is the same as the codebase), version of it.
    <?xml version="1.0" encoding="utf-8"?>
    <!-- JNLP File for GeekJokes 0.3 app -->
    <jnlp spec="1.0+"
          codebase="http://profile.iiita.ac.in/IIT2006117/javasoft/webstart/geekjokes"
          href="geekjokes.jnlp">
       <information>
          <title>GeekJokes App</title>
          <vendor>Vaibhav Mishra</vendor>
          <homepage href="http://scjpbeginner.blogspot.com"/>
          <description>Geeky Jokes</description>
          <description kind="short">Cshows random jokes</description>
          <offline-allowed/>
       </information>
       <resources>
           <j2se version="1.6+"
               href="http://java.sun.com/products/autodl/j2se"/>
           <jar href="GeekJokes0.3.jar"/>
       </resources>
       <application-desc main-class="Process"/>
    </jnlp>Very 'Geeky', BTW. ;-)
    Another few things I noted when I looked at it.
    1) There is a stray thread going after the JOptionPane is dismissed. The VM does not end, and the console (if you have it configured to pop-up for JWS apps.) stays on-screen.
    2) If all the jokes are prefixed by '* ' I would recommend removing it from every line of the source file and either re-adding it at runtime, or (preferably) not adding it at all (since it is redundant).
    3) Reconfigure the app. into a loop, and offer the user a JOptionPane with "Another Joke"/"End" instead of "OK".
    4) You can always remove that debugging line I inserted in the code to show the path to the Jar - it was just intended as a 'sanity check' during testing.
    5) Why is it Java 1.6+? JOptionPane was introduced in Java 1.2 with the first Swing implementations, and the I/O is compatible with Java 1.1.
    >
    Thanks again!!!!>Thanks are best expressed (to me) in the notation of a helpful/correct answer (which you have done), and the assignation of (the remaining) dukes*. ;-)
    * After all - checks the title - we have gotten entirely around those 'security restrictions' in a sandboxed application. The reason being that File objects are rarely the correct choice, for applets or JWS apps.

  • How to access a xml file stored in a jar file

    Hi all,
    We have a java web start app that uses the jasper reports libraries to produce pdf reports. When running and testing from the ide the prog works ok. However when we place the jar on the web server and run the web start app the prog complains "the system cannot find the file specified".
    The xml files are stored in the jar under a directory called reports. The code access the files like so. (We are temporarily writing the output file to c drive.)
    JasperCompileManager.compileReportToFile("reports\\airexportagy.xml","c:\\airexportagy.jasper");
    IS there a different way one is supposed to access these resources from a jar file using web start?
    THanks

    Always (well, almost always anyway) access resource files thru the classloader. Example:
    InputStream xmlStream = getClass().getResourceAsStream("/myresource.xml");
    This will find "myresource.xml" in the classpath. If you omit the "/" part, it will still attempt to find that file in the classpath, but expect to find it within the same directory hierarchy as the calling class (its package hierarchy).

  • Access JAR File while running App with Java Web Start

    Hello guys,
    I want to delpoy my application so that I can run it when I click on the appropriate button in a web page.
    I have a Jar file for all the files that the app needs. No, not all of the files are included.
    Indeed, I use JAR files such jdom.jar or postgres...jar that I must use in within my application.
    How can I access these JAR files knowing that I can't point to files in a JAR file A from within a JAR file B, if the JAR file B contains the JAR file A?
    The main JAR file that I put on the web server can be seen as the JAR file B and the other JAR files must be stored somewhere for the java classes within the main JAR file to have access to them.
    I wonder whether there is another way to structure the project.
    Thanks.

    Hi Andrew.
    I have followed your suggestions and here is what my .jnlp file look like:
    <tt>
    <?xml version="1.0" encoding="utf-8"?>
    <jnlp spec="1.0+" codebase="http://localhost:8080/koedops" href="beta.jnlp">
         <information>
              <title>KOEDOPS</title>
              <vendor>Pr. Fischer</vendor>
              <homepage href="http://localhost:8080/" />
              <description>Downloading koedops with Java Web Start</description>
         </information>
         <resources>
              <j2se version="1.6+" />
              <jar href="beta.jar" main="true"/>
              <jar href="jcalendar-1.3.3.jar" />
              <jar href="jdom.jar" />
              <jar href="postgresql-8.4-701.jdbc4.jar" />
         </resources>
         <application-desc main-class="general.Application" />
    </jnlp>               
    </tt>
    The three other jar-files reside in the same directory as the .jnlp file and the beta.jar file on the tomcat server.
    When I launch the application though nothing happens upon the download. In contrast, if I change the main class to a class file that requires no extra library, it runs perfectly.
    I can't be sure whether the jar-files are successfully accessed.
    Regards.
    Edmond

  • Unable to access jar file error !

    hello,
    i have built my netbeans project and obtained the hequalifies.jar file . unfortunately when i'm trying to run this jar file from the prompt command I'mgetting the error: unable to access jar file
    here is the command i'm typing:
    C:\Users\User\Documents\NetBeansProjects\hEqUALIFIES\dist>java -jar " C:\Users\U
    ser\Documents\NetBeansProjects\hEqUALIFIES\dist hequalifies.jar "
    anyone has any clue?
    10x!

    ok i'm gonna make it easier on you.
    i gess i found what is the problem but have no idea how to solve it.
    when i obtained the .jar file i also obtained a README.txt file in which it is written the following phrase:
    ** If a library on the projects classpath also has a Class-Path element*
    specified in the manifest,the content of the Class-Path element has to be on the projects runtime path.
    I'M SORRY BUT I DID NOT UNDERSTAND WHAT IS MEANT BY: what is "the projects runtime path"?
    the content of my manifest is:
    Manifest-Version: 1.0
    Ant-Version: Apache Ant 1.7.1
    Created-By: 10.0-b23 (Sun Microsystems Inc.)
    Main-Class: hequalifies.ui.HeQualifies
    Class-Path: lib/PlugIn
    X-COMMENT: Main-Class will be added automatically by build
    I'm having problem with lib/plugin.

  • Error message at start-up Unable to access Jar file

    I am a consumer, not a business...and not an IT professional. I am running Vista and have not installed any new software recently.
    At every start-up, I get a pop-up titled Java Virtual Machine Launcher. The message says "Unable to access jar file". C:\users\user\.jnana.jnana.tsa.
    Any idea how to fix this?
    Thanks in advance.
    Edited by: 794979 on Sep 15, 2010 5:31 AM

    ok i'm gonna make it easier on you.
    i gess i found what is the problem but have no idea how to solve it.
    when i obtained the .jar file i also obtained a README.txt file in which it is written the following phrase:
    ** If a library on the projects classpath also has a Class-Path element*
    specified in the manifest,the content of the Class-Path element has to be on the projects runtime path.
    I'M SORRY BUT I DID NOT UNDERSTAND WHAT IS MEANT BY: what is "the projects runtime path"?
    the content of my manifest is:
    Manifest-Version: 1.0
    Ant-Version: Apache Ant 1.7.1
    Created-By: 10.0-b23 (Sun Microsystems Inc.)
    Main-Class: hequalifies.ui.HeQualifies
    Class-Path: lib/PlugIn
    X-COMMENT: Main-Class will be added automatically by build
    I'm having problem with lib/plugin.

  • Problem in reading a resource file form JAR

    Problem in finding a resource file from the jar.....
    I have my code in the following directory structure
    rootDir -
         libDir -
              XMLEntities.res
         modelDir -
              File1
              File2
              File3
    Step1 - I create a jar file with root as modelDir and with all its files.
    Step2 - I add XMLEntities.res also to the root of the jar
    If I run my application using
    java -classpath ;C:\aip_build\build_dm\rmi_server_files\dm.jar; model.data_model.ActivateDataManager
    My application which uses Xalan.jar (lyong under ext directory in jdk) does not find XMLEntiries.res.
    If I use my application as under without creating jar my application does find XMLEntites.res
    Can anyone tell me why the application can not find the XMLEntities.res inside jar?

    Sorry I missed one line............
    Problem in finding a resource file from the jar.....
    I have my code in the following directory structure
    rootDir -
    ----libDir -
    --------XMLEntities.res
    ----modelDir -
    --------File1
    --------File2
    --------File3
    Step1 - I create a jar file with root as modelDir and
    with all its files.
    Step2 - I add XMLEntities.res also to the root of the
    jar
    If I run my application using
    java -classpath
    ;C:\aip_build\build_dm\rmi_server_files\dm.jar;
    model.data_model.ActivateDataManager
    My application which uses Xalan.jar (lyong under ext
    directory in jdk) does not find XMLEntiries.res.
    If I use my application as under without creating jar
    my application does find XMLEntites.res
    java -classpath
    ;C:\aip_build\build_dm\rmi_server_files\;C:\aip_build\b
    ild_dm\rmi_server_files\lib
    model.data_model.ActivateDataManager
    Can anyone tell me why the application can not find
    the XMLEntities.res inside jar?try loading the resources as a InputStream
    something like :
    InputStream is = NameOfLoadingClass.class.getClassLoader().getResourceAsStream("XMLEntities.res");
    Hope this might help you in some way.

  • How to raplace resource files in jar file by other files?

    Can I replace resource files (ex: some jpeg file which is in the jar file) when midlet execute on the phone. Is it possible?
    Usualy, we use getResourceAsStream(filename) to get resource data as stream.
    Is there some API function like 'setResource(filenmae,stream)' ??
    Assume that I have a javaME application which displays some image in the jar file.
    It is different from general image viewr program because it can display only
    image file in the jar file (it means image file is resource file of java applcation).
    In other words, when application executes, It shows always same image at first.
    but I want that user can change image displayed if user wnat to do. I want to embed
    authoring function into application. So user can replace resource file by other image files on the phone.
    How to do that?

    I already told you, you CAN'T replace resources in a jar file.
    [http://forums.sun.com/thread.jspa?threadID=5334325]
    Look into using rms to save content on a mobile device.
    Now do you have anything else you want to ask?
    db
    edit And it's also rude to repost the question here without posting a response on the other topic you started.
    Edited by: Darryl.Burke

Maybe you are looking for

  • Line Out: broken ground connection?

    Hi! At home, I ususally connect my MacBook Pro with my stereo using the line out socket to listen to music. Today, after coming home from work, I plugged in my stereo into the line out of my MacBook and all I got was some nasty buzzing. Just like if

  • Condition type maintained in Value basis

    Hello, Iam maintaining the ZADC condition in Pricing procedure for AED purpose... Now at present we are maiantaining the this condition in 4% (Maintaining the condition type as percentage basis). Now we are planning to maintain this condition in Valu

  • Recovering Logical Standby - Non-Guarded Schemas

    I'm making use of logical standby databases for our reporting environment. We are also making use of the capability of having a number of other schemas that havent come from the primary and are therefore not managed by data guard. Recently had a prob

  • HT2638 My Iphoto crashed today while on location. Please help me?

    I have tried all the stuff above but after I click any of the options the program closes. What is the filename of my Iphoto library please - the one I have to back up

  • Updates Adobe Reader

    After some problems and repairs on my pc I am unable to update my Adober Reader . I use Windows Millenium. My current version of Adobe is 5.0 Who can help me?????