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;

Similar Messages

  • 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();
    }

  • 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

  • How to modify files in the jar pack

    Is there any way to allow the classes to read and write the files or directories which are inside the same jar file?
    Thanks

    I think you can consider the jar file as a zip file and modify the content of it using
    java.util.zip package:
    http://www.java-tips.org/java-se-tips/java.util.zip/

  • How to read files from the menu prompt

    Hi all the experts here, help me plz
    this is the menu
    R - Read a batch of student marks from a file
    D - Display a table of student results
    Q - Quit from the program
    when user press R the program has to read a file. The default file name is results1.txt
    but my teacher is gonna change the file name when she tests it.
    so i can't put the fixed file name. i have to read the file name from the command
    prompt
    The user will type the file name and i just have to read that file..but..its hard for the
    biginner...THX guys

    help me guys plz im really stuck man
         public char promptMenu()
              System.out.println ("R - Read a batch of student marks from a file");
              System.out.println ("D - Display a table of student results");
              System.out.println ("Q - Quit from the program");
              char answer = Keyboard.readChar();
              return answer;
    after user press 'R'
    then i have to read a file whatever the user enters..

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

  • How to read file in JAR file (the one containing applet class)

    my applet needs to read a file (font file) that will be bundled in the jar file. how do i read that file?
    i tried using
    URL u = new URL("file:///myfont.ttf");
    u.openStream();i got AccessControlException. is there anyway for the applet to load file in the JAR file? i see applet can load image in the jar file so figured that it should be able to do so with some other type of file
    thanks

    The reason you're getting access violation is the way you code your URL -- it's pointing to a file on the user's local disk. If my.ttf is in the jar, try:
          URL url=myApplet.class.getClassLoader().getResource("myfont.ttf");Where myApplet is the name of your applet and the font file is assumedly kept in the same directory level in the jar file as the class file for your applet.
    ;o)
    V.V.

  • 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 some files inside the jar

    Hi,
    I have an applet that runs with JWS. The user can input some information and then I need to show this information in a web page. As the application can be run offline, I cannnot use JSP�s to generate the web page. The information is saved in a xml file, so I use a xsl parser to generate the html code. The problem is that I have to include some javascript files (.js). I put these files inside the jar, but, how can I read these files, or how can I reference these files from inside the html page ?
    Thanks !

    You can use getClass().getResource(classpath)
    to get a stream version of the data from your
    jar file. If you need to put it in a file, you
    can write that stream to a file in a temp directory.
    classpath is the classpath of your js file

  • How to read, write file inside the JAR file?

    Hi all,
    I want to read the file inside the jar file, use following method:
    File file = new File("filename");
    It works if not in JAR file, but it doesn't work if it's in a JAR file.
    I found someone had the same problem, but no reply.
    http://forum.java.sun.com/thread.jsp?forum=22&thread=180618
    Can you help me ? I have tried this for all night !
    Thanks in advance
    Leo

    If you want to read a file from the JAR file that the
    application is packaged in (rather than a separate
    external JAR file) you do it like this ...
    InputStream is =
    ClassLoader.getSystemResourceAsStream("filename");Better to use
    this.getClass().getClassLoader().getResourceAsStream();
    From a class near to where the data is. This deals with multiple classloaders properly.

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

  • Reading a file in the JAR

    i have a jar with class files and xml files in it. my application uses this jar and a particular class has a link to the xml. but while compiling, it shows path not found. the application couldnt read the xml file in the jar. how to set the path or read the xml file
    XML file in JAR:
    SQLMaps/admin/sample.xml [folder structure inside the jar file]
    my application has a path like SQLMaps/admin/sample.xml
    but how do we point to the xml file in the jar
    Regards
    Pradheep

    thanks anyway
    but i need the application to read the xml file in the jar file
    to be more clear.
    the jar file has xml in a specified folder.

  • How to read and update the value of property file

    Hi,
    I am not able read the values from property file.
    Please tell me how to read and update the values from property file using Properties class
    This is my property file : - Config.properties its located in D:\newfolder
    Values
    SMTP = localhost
    Now i need to change the value of the SMTP
    New value :
    SMTP =10.60.1.9
    Pls Help me
    Thanks
    Merlin Rosina,

    Post a small (<1 page) example program that forum members can copy and run that demonstrates your problem.

Maybe you are looking for

  • Weblogic-cmp-rdbms-jar.xml for One-To-Many unidirectional relationship

    hi, I am trying to create a simple cmp One-To-Many unidirectional relationship and deploy the same in weblogic. Can someone help me with the weblogic-cmp-rdbms-jar.xml. Am attaching the weblogic-cmp-rdbms-jar. xml tht i am using as also the correspon

  • Camera Raw update 4.2

    I have just loaded CS3. I have tried multiple time to update to CR 4.2 using Adobe Updater. My system stops mid way though the process each time. All other updates went through with no issue.

  • Joining 2 tables in oracle database using SQL

    I want to join 2 tables together before executing a statement. problem is one is a table of users, who have userID's and the othet table is a table of events that are owned by a userID, ie can have many events by same userID. i want to retrieve foren

  • Change log of cube

    Hello experts, I have an InfoCube that is cleared and reloaded every day. There is a log or a table where I can see the data loaded in the elapsed days? Thanks in advance, Vito

  • Where do I find locations under settings?

    I Have an iPhone 6 and locations is not working when I try to check in on facebook. it says go to Settings then Locations but I can't find it. Is it under another tab? THank you tina