Accessing files outside the jar

Greetings,
I've got a jar file with some classes, which is in a directory. In this dir there are also some resources. How to access those resources from inside the jar?
Thanks in advance,
imaginner

Try this...
In your class, add this line...
String path = System.getProperty("user.dir");
it will give the path of the folder from which you are running
your jar file. To this path, add your properties file name
and start reading it.....
For example:
If i have a properties file which both :
1) should be able to read and edit by users and
2) should be accessible by classes in jar file....
I would use the above concept like this.... in my class.....
String path = System.getProperty("user.dir");
Properties props = new Properties();
props.load(new FileInputStream(path+"yourPropertiesFileName"));
Hope it helps...
Vijay

Similar Messages

  • Accessing files outside the root of the site.

    Hi All
    On my web host space I have access to a directory outside the
    root of the
    website i.e. "private"
    I want to store files there for download after users have
    purchased them.
    I want to put them here to stop people ripping the files off
    by guessing the
    link or useing a website copier.
    What I plan to do is send a link to the user via email, this
    link will then
    go to a download page which records the user has accessed the
    file and then
    have the page automatically download the file.
    I can do this no problem if I have the files in a directory
    under the root
    of the site but how can I link to the files outside the root?
    TIA
    Bren
    Why do I climb mountains? Simple! because they are there
    www.3peakschallenge.co.uk

    Sorry forgot to mention I am using ASP VB
    Cheers
    Bren
    "Bren" <[email protected]> wrote in message
    news:ejgd9n$427$[email protected]..
    > Hi All
    >
    > On my web host space I have access to a directory
    outside the root of the
    > website i.e. "private"
    > I want to store files there for download after users
    have purchased them.
    > I want to put them here to stop people ripping the files
    off by guessing
    > the link or useing a website copier.
    > What I plan to do is send a link to the user via email,
    this link will
    > then go to a download page which records the user has
    accessed the file
    > and then have the page automatically download the file.
    > I can do this no problem if I have the files in a
    directory under the root
    > of the site but how can I link to the files outside the
    root?
    >
    > TIA
    > Bren
    > --
    > Why do I climb mountains? Simple! because they are there
    > www.3peakschallenge.co.uk
    >

  • How to read files outside the jar ?

    Hi all,
    One of my classes inside jar needs to read XML file that resides in the same location where the jar sits. I use MyClass.getClass().getResource("MyXMLFile.xml") but it keeps returning null.
    If I place the XML file inside the JAR, I can find it using above methods, but since I want the user to easily edit the XML file without opening the jar file and detach the XML file, I choose not to include the XML file inside the jar.
    Any help would be greatly appreciated.
    Setya

    Thanks for the dukes.
    My JDBC post on this forum discusses the issues of
    using Class-Path in your jar file. It works, but it
    may vary from system to system.
    Thanks also from my side: I have read recently your discussion about reading files in the jar's directory, since I had the same problem. So I was really glad to see your solution. However, I had one more problem, namely that I'm running my application sometimes from the jar, sometimes from the classes directly (debugging). In order to have always the correct path (although a different one) I have added some more lines to deal with that case. I hope that will be useful for you as well!
    Dieter Profos
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import java.net.URL;
    * @author pkwooster
    * @author Dieter Profos
    * @version 1.01 04/03/26
    public class ReadOutside extends Frame {
    private TextArea textArea;
    public static void main(String[] args) {
    // Create application frame.
    ReadOutside tc = new ReadOutside();
    tc.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    System.exit(0);
    // Show frame
    tc.setSize(600,250);
    tc.setVisible(true);
    public ReadOutside() {
    textArea = new TextArea(20,80);
    add(textArea);
    readOutside(this);
    public void readOutside(Object o) {
    System.out.println(getCodeBasePath(o));
    /** Gets the absolute path of the directory where the JAR or CLASS file is
    * located. If the application is run from a jar file, the directory of the
    * jar file is returned; if it is run from a class file, the method will
    * return the directory path of the class file.
    * @param o The main class of the application.
    * @return The absolute directory path, or null if neither the class nor a
    * jar file could be found.
    public String getCodeBasePath(Object o) {
    Class c = o.getClass();
    URL url;
    // get the class name
    String className = c.getName();
    textArea.append("class name = " + className + "\n");
    // replace package periods by file separators
    className = className.replace('.','/');
    ClassLoader cl = c.getClassLoader();
    if (cl == null)
    cl = ClassLoader.getSystemClassLoader();
    url = cl.getResource(className + ".class");
    String xPath = url.toExternalForm();
    textArea.append("url = " + url + "\n");
    textArea.append("extPath = " + xPath + "\n");
    // make sure that the path starts with jar:file:
    if (xPath.startsWith("jar:file:")) {
    // remove jar:file: + the subsequent file separator
    xPath = xPath.substring("jar:file:".length()+1);
    int n = xPath.indexOf("!");
    if (n < 0)
    n = xPath.length();
    String jarPath = xPath.substring(0, n);
    textArea.append("jar file path = " + jarPath + "\n");
    n = jarPath.lastIndexOf("/");
    String jarDir = jarPath.substring(0, n+1);
    textArea.append("jar dir = " + jarDir + "\n");
    return jarDir;
    else { // if program is run from its class file (development phase!)
    if (xPath.startsWith("file:")) {
    // remove file: + the subsequent file separator
    xPath = xPath.substring("file:".length()+1);
    textArea.append("class file path = " + xPath + "\n");
    int n = xPath.lastIndexOf("/");
    String classDir = xPath.substring(0, n+1);
    textArea.append("class dir = " + classDir + "\n");
    return classDir;
    return null;

  • How to access files outside a .jar file netbeans project

    Hi, i need to access a file outside a built project inside netbeans. Ideally i would like this file next to the .jar file as myapp.properties. If possible i would like it so that when i am compiling and running the project in netbeans the file can be with the class files or something along those likes. Either way it would be nice to have different code for built projects and just running them outside a jar.
    Heres what i got so far
    properties = new Properties();
                InputStream in = this.getClass().getResourceAsStream("applications.properties");
                properties.load(in);
                in.close();this only works if the file is next to the classes. (think thats called the classpath ? )
    Thanks for any replies!!

    Your wrong code:
    properties = new Properties();
    InputStream in
    = this.getClass().getResourceAsStream("applications.properties");
    properties.load(in);
    in.close();A right code:
    // basic assumption 1: applications.properties
    //  is a pure ISO 8859-1 text file
    // basic assumption 2: the file applications.properties
    //  is stored in the same directory where your
    //  jar file is stored
    properties = new Properties();
    try{
      FileInputStream in      // assume current dir
       = new FileInputStream("applications.properties");
      properties.load(in);
      in.close();
    catch (Exception e){
      e.printStackTrace();
    }

  • Creating a JAR in Eclipse...can't access files in the JAR properly.

    Hi all! I'm a newbie at JAR creation, and am having troubles. I have a project that loads images from image files in my project. I can create the JAR and all, and it runs, but the buttons that have ImageIcons with those IO loaded images are blank. I've tried to include the images when creating the JAR, but it keeps acting like the images never existed. When I run the JAR and have the images separately included in the directory (instead of packing them up too), it won't work as well...UNLESS those images are put in my $HOME directory (Linux).
    Does anyone know how I can properly refer to the images that I'm trying to pack into the JAR from within the JAR? Or, is there a way for the JAR to understand where those images are supposed to be (redirect the focus from the $HOME directory to the JAR's directory)? Any help would be greatly appreciated! :)
    -Keith

    Hi,
    Can the user execute the program through explorer? In Windows Server 2003, the Users group does not have Read and Execute permissions to the command processor (Cmd.exe). 
    You could refer to the article below to resolve the issue:
    "Access is denied" error message when you run a batch job on a Windows Server 2003-based computer
    http://support.microsoft.com/kb/867466
    Best Regards,
    Mandy 
    We
    are trying to better understand customer views on social support experience, so your participation in this
    interview project would be greatly appreciated if you have time.
    Thanks for helping make community forums a great place.

  • How to access a class file outside the package?

    created a two java files Counter.java and TestCounter.java as shown below:
    public class Counter
         public void print()
              System.out.println("counter");
    package foo;
    public class TestCounter
         public static void main(String args[])
              Counter c = new Counter();
              c.print();
    Both these files are stored under "D:\Test". I first compiled Counter.java and got Counter.class which resides in folder "D:\Test"
    when i compile TestCounter.java i got the following error message:
    D:\Test>javac -classpath "d:\Test" -d "d:\Test" TestCounter.java
    TestCounter.java:6: cannot find symbol
    symbol : class Counter
    location: class foo.TestCounter
    Counter c = new Counter();
    ^
    TestCounter.java:6: cannot find symbol
    symbol : class Counter
    location: class foo.TestCounter
    Counter c = new Counter();
    ^
    2 errors
    what could be the problem. Is it possible to access a class file outside the package?

    ya that's fine..if we have two java files where both resides in the same package works fine or two java files which donot have a package statement also works fine. But my doubt is, i have a Counter.class which does not reside in a package and i have a TestCounter.class which resides in a package "foo", in such a scenario, how do i tell to the compiler that "Counter.class resides in such a path, please look at that and give me TestCounter.class". i cannot use import statement to import Counter.class in TestCounter.java because i donot have a package for Counter.java.

  • Java Files inside the jar file cannot be read or accessed through Eclpse

    The Java File inside the jar file of the eclipse cannot be accessed through the Eclipse . It shows error for the modules in the jar file .
    But when compiled with adding the jar files to the class path the compilation is successful .
    How can i browse through the files in the jar like going into the function definition .
    TIA ,
    Imran

    Open MPlayer OSX and show the playlist (command-shift-p) then drag the file into the playlist. Click the file in the playlist and click the "i"nfo button. What does it list for file, video and audio format?
    Not all of the codecs used in avi and wmv files are available for OS X so I'm guessing your file happens to be using one that isn't...

  • How can I restrict access to cloud storage from Creative Cloud? We don't want our users putting files outside the organization.

    We need to restrict our users from storing files outside the organization. How can we restrict this capability?

    They have Cs6, however I need to have my own copy, and the highest I can go with my system is CS5, maybe even 5.5. I've a small budget, and most copies are being sold for massive amounts because they're like collector items. I've seen the ones actually affordable within my range from sellers that arent trustworthy, or they're updates which I can't use. I had Cs2, but with updates to operating systems they stopped working. Thank you for your kind assistance.

  • How to read a file outside my .jar

    Hello!
    I have my j2me application in a .jar file , and my application needs to read a .txt file which is outside my .jar but in the same directory.
    I tried to do :
    InputStream input = getClass().getResourceAsStream("/myfile.txt");
    as well as
    InputStream input = getClass().getResourceAsStream("myfile.txt");
    but nothing is working...
    Could you help me, please??? I'm getting crazy with this :(
    Thanks in advance!

    Thanks sabre150,
    sabre150 wrote:
    You cannot update a running jar file. I am sorry. I didn't know about it. Thanks to point out.
    There are two ways I approach this depending on my exact requirements -
    1) use the java.util.prefs.Preferences APII will try this one
    >
    2) if not already present I copy the preferences file from the jar to a known place. I use a directory in the user's home directory and normally make the directory name the program with a '.' prefix.
    One cannot access files in a jar file using the File API. One needs to use the getResource() or getResourceAsStream() methods on Class or ClassLoader.

  • How to read a file inside the JAR file

    Hi All,
    I want to save some preferences in a file called "preferences". I kept the preferences file under my java package.
    If i am running the code inside the NetBeans 6.9 IDE it's working file. But once i have created a JAR and try to run the application, it couldn't find the path.
    Please help me that how to resolve this issue. I don't want to save this preferences file outside of my JAR (i.e) within my java package.
    Here is the code,
    package mypackage;
    import java.io.BufferedReader;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    public class ReadFile
        private void writeFile()
            try
                OutputStream out = new FileOutputStream(getClass().getClassLoader().getResource("mypackage/preferences").getPath().replace("%20", " "));
                PrintWriter writer = new PrintWriter(out);
                writer.println("Hello Java!");
                writer.close();
                out.close();
            catch (Exception ex)
                System.out.println(ex.getMessage());
        private void readFile()
            try
                FileInputStream fi = new FileInputStream(getClass().getClassLoader().getResource("mypackage/preferences").getPath().replace("%20", " "));
                BufferedReader br = new BufferedReader(new InputStreamReader(fi));
                System.out.println(br.readLine().trim());
                br.close();
                fi.close();
            catch (Exception ex)
                System.out.println(ex.getMessage());
        public static void main(String[] args)
            ReadFile read = new ReadFile();
            read.writeFile();
            read.readFile();
    }If i run the JAR, i get the following error message,
    {color:#ff0000}*file:\my jar path\jarname.jar!\mypackage\preferences (The filename, directoryname, or volume label syntax is incorrect)*{color}

    Thanks sabre150,
    sabre150 wrote:
    You cannot update a running jar file. I am sorry. I didn't know about it. Thanks to point out.
    There are two ways I approach this depending on my exact requirements -
    1) use the java.util.prefs.Preferences APII will try this one
    >
    2) if not already present I copy the preferences file from the jar to a known place. I use a directory in the user's home directory and normally make the directory name the program with a '.' prefix.
    One cannot access files in a jar file using the File API. One needs to use the getResource() or getResourceAsStream() methods on Class or ClassLoader.

  • Accessing Files within a jar - Problems.

    So i have the following code in my program and when i goto run the jar file i get NPE's:
    URL fileURL = getClass().getResource("resources/cfg/portlist");
                    BufferedReader portFileBuff = new BufferedReader(new InputStreamReader(fileURL.openStream()));Now my jar file has resources/cfg/portlist in it and i cannot figure out why this isnt working for me when it works just fine in another program i have. I feel im missing out on some framing issue. Any Suggestions?

    Hello,
    I have the same problem when trying to log "log4j" from a jar....
    Here is my code that generate the error:
    static{
              DOMConfigurator.configure("config"+File.separator+"log4j.xml");
    Obviously, the file log4j is in my jar in the directory config.
    This code works well outside the jar.
    It semms that I got also the same problem on library that are in my jar under the directory "lib"....
    Any idea..?

  • Problems while accessing images outside the web document-root folder

    Our application runs on Oracle application server on Linux. Facing problems while accessing images outside the web document-root folder. This works with changes in global-web-application.xml by including the <virtual-directory> tag. The same change does not work when done on Linux machine. It is unable to find the image. Please help in resolving this issue.
    </locale-encoding-mapping>
    </locale-encoding-mapping-list>
    </web-app>
    <virtual-directory virtual-path="/img" real-path="/home/eposuat/" />
    </orion-web-app>
    Code in the jsp:
    <img width=700 height=700 src="/img/3.tif"></img>
    <img width=700 height=700 src="/img/WB.gif"></img>

    This is one of the least satisfactory aspects of site management in Dreamweaver, and several developers, including myself, have been pressuring the Dreamweaver team for some years to improve this. Who knows? They might eventually take notice.
    The only way to do this at the moment is to create two site definitions, one nested inside the other. Set up the site definition normally based on htdocs as your site root. Then create a new site definition based on site. Dreamweaver will nag you that it can cause problems, but it won't actually stop you from doing it. The only potential problem is with site synchronization.
    The problem with using site as the only basis for your site definition is that Dreamweaver automatically puts things like the Connections, Scripts, and other folders in the site root. So, everything ends up at the wrong level of the site hierarchy. Quite frankly, the whole thing is a bit of a pain. Dynamic site development was added to Dreamweaver only in version 6 (Dreamweaver MX), and no one had really thought through the need to store files outside the site root.

  • Loading Image outside the jar

    I have a .jar program that saves and loads imagens from a folder outside the jar. In my directory I have:
    myProg.jar
    images(folder)
    This is the way myProg.jar saves the images:
    BufferedImage myImage; //myImage is initialized somewhere else
    File file = new File("images/Pic"+temp+".jpg");
        try{
        ImageIO.write(myImage, "jpg", file);
           }catch(IOException io){}
    }catch(AWTException ea){}When I check the image is saved in my folder "images"
    Then, the prog tries to load the images this way:
    URL url = getClass().getResource("/images/"+name+".jpg");
    ImageIcon icon;
             if (url != null) {
                  icon = new ImageIcon(url);
                  picture.setIcon(icon);
             else {
                  url = getClass().getResource("/images/street.jpg");
                  icon = new ImageIcon(url);
                  picture.setIcon(icon);
             }Here I have an exception : Exception in thread "AWT-EventQueued-0" java.lang.NullPointerException
    I checked the url and it�s ok.
    Hope someone help.

    Well, I modified the getJarPath method to this:
    String getJarPath1(){
              String path=System.getProperty("java.class.path");
              for(int i=0;i<=path.length()-1;i++)
                   if(path.charAt(i)==';'){
                        return path.substring(0,i);
              return "";
         }Now I got the path I really need, for example:
    C:\Program Files\Eclipse\Workspace\myProject\images\pic.jpg
    Though, the picture is not loading. Here is what I am doing:
    String path=getJarPath1()+"\\images\\" + name + ".jpg";
    //path=C:\Program Files\Eclipse\Workspace\myProject\images\pic.jpg -> correct path
    URL u=null;
    try{
                 u = new URL(path);   //u is always null! why?
                }catch(MalformedURLException mf){}
    if(u!=null)
             try{
             icon = new ImageIcon(u);
             picture.setIcon(icon);
             }catch(Exception bla){}
             else {
             }What�s happening is that my "path" got the correct path, but when I put it in the URL it�s becoming null.
    The picture and the folder are in the correct place.
    I hope someone helps. Thx!

  • Updating an XML file inside the Jar executable

    Hello all!
    I would like to ask how can i update an XML file that is packaged inside my jar file?
    For intstance:
    I have a Java Application in NetBeans
    Inside a package i have constructed a custom .xml file.
    I can read from this file using
    .....getClass().getResourceAsStream("/.../file.xml")and after that using XPath for querying and works fine.
    I want to update an entry in my xml file so the jar contains now the newly updated file.
    Thanks everyone who spends his time to read this. Hope someone can help me.

    Even if it were possible, it would be a bad idea. A jar file is something you deploy. It can be really hard to manage ongoing maintenance if the thing you deploy changes after you've deployed it.
    Just create a file, in an appropriate place given the user's OS, to hold data that changes after the jar has been deployed. Your application will still be in a single jar; it's just that the application will happen to create additional content outside the jar.

  • Refer ResourceBundle/external resources like icons from outside the Jar

    Hi,
    I have a swing application and I am using ResourceBundle to support internationalization. I also refer some icons.
    Now I have packaged my class file in a jar and I want to refer ResourceBundle and icons from outside the jar. This is to support runtime changing of values and icons without needing to recompile.
    When my code is in Eclipse and I try to refer the resource bundle, it is working fine. But as soon as I have a jar and try to refer the resource bundle from the class path, I am getting MissingResourceException.
    Please help.
    Regards,
    Manu

    As per my actual requirement, I wanted to have these properties files (resource bundles) and icons directly on the classpath, so that user has the convenience to modify them.
    I am not able to do so. I included the directory containing icons and resource bundle on the classpath, but i am not able to refer these icons from the main jar.So it works when the resources are in a 2nd jar, but not when they are in a folder that is in the classpath?
    Is the relative path of the resource files the same in both cases?
    In the simplest case (no nested folder), the icons are in the root of the jar, and the folder-equivalent is that they should be straight in the folder which you added in the classpath.
    Or are they (frequent case) in a nested folder, along your package structure, such as com/yourcompany/yourapp/gui/icon.jpg?
    In this latter case, you must not put folder "gui" in your classpath, but merely the folder which contains "com".
    I am just wild-guessing of course, for a more specific reply could you post a sketch of your jar/folder structure (in tags) and your command line, including
    the classpath part, in both the case that works and the one that doesn't?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Maybe you are looking for