Relative Paths in Java, omg

Ok I just figured out that, what seemed to be a relative path is in reality the relative path of the starting program.
For instance:
We suppose, I got a directory: "D:/Java/Project"
in this dirrectory, there are .class files, .java files and folders which holds data like music and graphics.
normaly in all my classes the path goes like this:
for example the audio class : load every audio file from "audio/" + specific audio file name
until now everything like that worked, but only because I started the Project from within this very directory.
Assuming I got in "D:\Java" a batch file, that starts my project, like this: "java -cp ./Project MyClass"
if I run it, my code suddenly looks at "D:/Java/audio" for audio files instead of "D:/Java/Project/audio"
which means the relative path is in reality the relative path of the starting program and not from the class itself.
So how could I possibly get a relative path, telling my program, my audio class for instance again "stay where this class file is, then go to audio/ and there you got your audio files", regardless at where I start my project ?

If you do
new File("some/relative/path/foo.bar");it is relative to the directory you started Java in.
If you want to use the classpath (or load things from inside JAR files) you should use
this.getClass().getClassLoader().getResourceAsStream("some/relative/path/foo.bar");using "/" regardless of your OS.
I think you can also use
this.getClass().getClassLoader().getResource(...)which gets a URL instead of a stream, and then maybe you can
open the file directly with the URL.
and you can also use
Thread.currentThread().getContextClassLoader().get...

Similar Messages

  • Get the relative path for java class

    How to get Relative path for java class which is inside in web-inf directory in webapps

    ajay.manchu wrote:
    Hi gimbal2,
    My Requirement is i need to run a java class from batch file,when i created batch file in that i need to mention the complete path of the java class,so instead of mentioning that i want to provide only java class name,thats why i asked that one..
    can u help me regarding that....
    Thanks in advanceI wonder how that would work then. Let's take a fictive example. You have a class com.mycompany.myapp.Foo. This would mean that the class is stored in some directory like this:
    c:/webrootdir/myapp/WEB-INF/classes/com/mycompany/myapp/Foo.classTo be able to run such a class from the commandline using Java, you would have to invoke this command:
    java -cp c:/webrootdir/myapp/WEB-INF/classes com.mycompany.myapp.FooHow would knowing the exact path to this class help you?

  • Relative paths in java

    Hi,
    I've got another little problem and I hope anybody can give me an idea how to solve it:
    I wrote a java-class that has an attribute called filename, that stores the path to an xml-file. I read from this xml-file using jdom.
    I deploy this class to the jboss-server by copying a jar-file (containing this class) to
    C:\jboss-4.0.0\server\all\deploy
    Everything works fine, but I would like to store that xml-file in another directory, for example
    C:\jboss-4.0.0\server\lib
    This might look different on another system depending on where jboss is installed, for example
    C:\folder1\folder11\jboss-4.0.0\server\lib
    How can I use relative paths in java, so that I can tell my filename-variable where the xml-file is, independently from the jboss-installation???

    I would suggest using the class path to find files.
    e.g.
    InputStream is = getClass().getClassLoader().getResourceAsInputStream(fileName);
    This allows the file to be anywhere in the class path, even in a jar file or http url.

  • How to read/know/use  relative paths in java files ?

    I am able to access files in java after using the
    String TxtURL = "file:///c:/files/TEXTS/";and then loop
    = new File(ma.TxtURL +filename );However , I need to use this in several drives , C , D E etc , how can I use relative path ?
    I used these but they didn't work
    String TxtURL = "file:///TEXTS/";
    String TxtURL = "file:////TEXTS/";
    String TxtURL = "file:///./TEXTS/";
    String TxtURL = "file:///../TEXTS/";

    ya batch , I want to run a java program from batch file
    java C:\...\fileand as u know that C will change , so any suggestions/solutions ?
    thanks

  • Relative Paths in Java Program

    Hi All,
    In one of the java programs i am trying to read a properties file using the Properties class
    Please find the code below
    private static final String magicPropFile = "config.prop";
    Initial.magicProps = new Properties();
    Initial.magicProps.load(new FileInputStream(Initial.magicPropFile));
    This throws a FileNotFoundException
    I have placed the file in the same directory as the .java files. I am using Eclipse IDE. The files are placed in a package com.xyz.sample
    All the .java and the prop files are in the same directory
    It works fine when i give the absolute path from my Desktop.
    Can anyone tell me that is the file placed properly or any change in the code that needs to be done?
    Rgds
    Aditya

    Hi aditya,
    check your java class path that it contains "." (dot) at the end. Here dot represents the inclusion of current directory.
    Even if u have the "."(dot) on the classpath and still you are facing the issue, give file name as "\config.prop"
    Hope this may helpful for u.
    thanks.
    --Subbu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to mention a  Relative path in a java file

    How to mention the relative path of the file in fileinputstream?
    The directory structure is as follows,Inside the **model** folder i have a java file called GetContents.java
    I need to refer the input.xls file inside the template folder in GetContents.java.file.
    I tried new FileInputStream("..\\..\\..\\template\\DevContentsTemplate.xls") cos the GetContents.class file will be inside webcontent\web-inf\classes\model\GetContents.class and I thought if i use the above relative path , it should refer webcontent\web-inf\template\input.xls
    But it throws a file not found exception.
    ContentValidation
    - src
    -action
    -model
              -bean
              -form
              -utils
    -WebContent
                   -WEB-INF
                        -classes
                        -action
                   -model
                             -bean
                             -form
                             -utils
                        -lib
                   -template
                             -input.xls
    Kindly help.
    Thanks.

    morshed_nsu wrote:
    if so then for one ../ you will reach classes folder. for another you will reach the folder containing src, classes, templates etc.
    So you do not need 3 escapes.I posted that same answer 7 hours before you did! What part of your answer is any additional help compared to mine? It's fine to give someone another answer, but there's not much point in giving the SAME answer 7 hours later. If it were a few seconds or a few minutes later, I would excuse you for having tried to post at the same time. But, 7 hours?! Please read the existing answers next time, not just the original post.

  • OpenScript/How to add .jar file to Java Code in relative path

    Hi all,
    I want to add a .jar file which can be executed separately (like "java -jar A.jar") to my recorded Java Code.I've read this wiki http://everest2.us.oracle.com/wiki/Generic_JAR_Project about how to add a .jar file to "Assets", however, I cannot figure out how to use the .jarr file in Java code,I mean , how to get this .jar file like the method the databank added in "Assets"?
    Things I did are as followed:
    1.Execute my .jar file in OpenScript Java code with absolute path like this:
    String cmd = "C:\Users\A.jar";
    Runtime.getRuntime().exec(cmd);
    This does work, but must set a absolute path in Java code like "C:\User\A.jar" ,which is not the workaround I want (I need my scripts can be run on other machines).
    2.Try to get its current path with following codes:
    File directory = new File(".");
    String currentPath=directory.getCanonicalPath();
    However,though this can get its absolute path (which is the the project path) in Eclipse like "C:\Users\Workspace\testProject", this only gets "C:\OracleATS\openScript" in OpenScript.
    I thought to copy my .jar file to the project path , got its current path in java code first,then can know the path of .jar file, but this workaround failed because of the above reason.
    I notice that in the "Assets" there are "Databanks","Object Libraries","JAR Files","Scripts". Since the databanks and scripts that added to "Databanks" and "Scripts" can be got or run in Java Code like:
    *getDatabank("DatabankName").getNextDatabankRecord(); String data = eval("{{db.DatabankName.data}}");*
    *or getScript("ScriptName").run();*
    *Is there a method to get and run the jar file added to "Assets\JAR Files" like the above?*
    Thank you very much!
    Regards,
    Angyoung

    Hi DM,
    Thanks for your reply!
    I've found a workaround,which is calling OpenScript's APIs ,such as this.getScriptPackage().getRepository() and this.getScriptPackage().getWorkspace(),etc to locate the .jar file.
    And this workaround can still work even though the script is run on other machine.
    Sorry to reply you so late!
    Regards,
    Angyoung

  • Relative path for servlet property file.

    I have the following java file. When I use the absolute path for the configFile, it works. I would like to know how I could use it as relative path as in installation, the name of the directory could change.
    How do I fix the problem? Thank you.
    ---------------------- LoadProperties.java ----------------
    import java.util.*;
    import java.io.*;
    public class LoadProperties {
    private String driver="";
    private String dbURL="";
    private String login="";
    private String password="";
    static public void main(String[] args) {
    LoadProperties lp = new LoadProperties();
    } // main
    public LoadProperties() {
    //String configFile = "C:/1LMS/web-app/WEB-INF/config/db.properties";
    String configFile = getClass().getResource("config/db.properties").toString(); <--- This line could not find the db.properties file.
    Properties Prop = new Properties();
    try {
    FileInputStream configStream = new FileInputStream(configFile);
    Prop.load(configStream);
    configStream.close();
    } catch(IOException e) {
              System.out.println("Error: Cannot laod configuration file ");
    driver =Prop.getProperty("driver");
         dbURL = Prop.getProperty("dbURL");
         login = Prop.getProperty("login");
    password = Prop.getProperty("password");
    printResult();
    } //Load Property
    private void printResult() {
         System.out.println("Driver = " + driver);
         System.out.println("dbURL = " + dbURL);
         System.out.println("Login = " + login);
    System.out.println("PSWD = " + password);
    } // class

    hi there,
    had the same problem... you need to use following API:
    http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)
    In your case something like that:
    // get the servlet context
    ServletContext context = getServletContext();
    // directory name where the file is located
    String realPath = context.getRealPath("/config");
    // get real path to your file
    String propertyPath = real+"filename.txt";
    hope that helps!!
    minu

  • How to give relative path in web.xml?

    Hi All,
    Im creating a servlet which has to load the properties file.
    I don't want to give the location of the properties file as ABSOLUTE PATH. But I'm unable to provide the same as RELATIVE PATH.
    When I give the path is given as ABSOLUTE PATH (drive:/dir/) it is working. But if I give the RELATIVE PATH(../), the same is not working.
    Kindly help me in this.
    Regards,
    Kumar Madhavan.
    My web.xml file is:
    <?xml version="1.0"?>
    <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
    <web-app>
         <display-name>NGT - ASCII</display-name>
         <description>Application for Safety Critical Information vIew.</description>
         <welcome-file-list>
              <welcome-file>ASCII.html</welcome-file>
         </welcome-file-list>
         <context-param>
              <param-name>asciifiledir</param-name>
    <!-- This is the tag in which I would like to
              <param-value>../</param-value>
         </context-param>
    </web-app

    Hi.
    Exclude the directory path from the <param-value/> in
    the web.xml and just keep the property file name.
    Place the property file in the classpath and load it
    like this from the servlet:
    Properties props = new Properties();
    String propFileName = "" // Read param-value from web.xml
    try {
    InputStream is = TheServlet.class.getResourceAsStream(propFileName);
    props.load(is);
    } catch (Exception ex) {
    System.out.println("Prop file not in classpath!");
    /Jesper

  • How can I use a relative path in a Virtual Directory tag?

    That is probably a bit vague, so I will explain in more detail. We are using BEA
    WL Portal 7.0 and our team is developing multiple portal applications. We have
    a core set of portlets (consist of JSPs) that we need to reuse in multiple portals
    (Web Apps), however from a version control perspective they need to reside in
    one common location. So, the solution I came up with is to use a virtual directory
    for the the common directory and add this to weblogic.xml for each web app. This
    works fine. However, each developer has different directory names for their project...ClearCase
    view names to be specific... plus we have integration views, QA views, etc...
    so we can't have any "C:\mystuff\mydomain" absolute paths anywhere in the portal
    configuration. Does anyone know of a way to use a relative path for a virtual
    directory? I have tried various versions of ../../ for example to try to backup
    and then recurse down to the directory, but this is not working. Any ideas?
    By the way this is basially just a hack for development, when we package the WAR
    for QA, Prod, etc... we copy needed files and there are no virtual directories.
    In other words, I don't care how "creative" solution is :)
    This is what I have right now, which I need to replace with a relative directory
    name:
    <virtual-directory-mapping>
    <local-path>C:/Projects/TouchPoint_v1.0_Fix/tp_portal/bipiportals/beaApps/portalApp/tp-shared</local-path>
    <url-pattern>*</url-pattern>
    </virtual-directory-mapping>

    Well, in fact you can in a special case :
    - The file you want to access is in the same directory than the applet (or in a sub-directory)
    If this condition is OK, you can open the file using :
    java.io.InputStream MyInputStream = <YourAppletClassName>.class.getResourceAsStream("sidira_interactif2.svg")
    With this stream, its easy to read the file content.

  • Relative Path and FileWriter

    I have the following code and it works fine when running standalone. I have to add that entries.xml and my Java file are in the same package.
    String filename = this.getClass().getResource(".").getPath() + "entries.xml";
    FileWriter writer = new FileWriter(filename, false);But when I run this inside Tomcat, getResource(".) is returning me my tomcat path instead of where my Java class is located. How can I fix this to work in both places and use relative paths?
    Thanks in advance.

    Moving to another forum. I think this is an incorrec forum for this question.

  • Can't use relative paths in jsp pages or javabeans

    Hi everyone,
    Can someone please help me with this little problem.
    When I want to use in a JSP page the object 'FileReadInput' to read in a file, it can't find when I only give the filename. The target file and source file are in the same directory so I would expect if I only give the filename, it will automatically search in the current directory. But when I give the complete absolute path, everything works fine. Is it possible to use relative paths in a jsp or javabean file?
    By the way, I am working with JDeveloper from Oracle. (maybe that has something to do with my problem)
    Can someone help me???
    Thx

    My dear friend,
    It will not work at all. coz, for any jsp file, ur application server will create a .java file and then .class file in a directory other than the directory where ur .jsp file present. that's why, ur file to be read can't be found. that's why use the following.
    String path=getServletConfig().getServletContext().getRealPath("/")+File.seperator+"yourfilename";

  • How to get a relative filepath using Java?

    Hi,
    I'd like to write a custom application for something I'm doing at work. Basically, I need to find the relative filepath from one file to another. Like, if I start in a subdirectory of directory A with file abc.htm, I want to use Java find the relative hyperlink I would put in abc.htm to link to another file in another subdirectory of A. Something like "../Subdirectory/xyz.htm" (where xyz.htm is the file I want to link to) returned as a string.
    The reason it needs to be a relative filepath without any references to named directories is that the application with all the hyperlinks in it will eventually reside on a different server or servers. The people who put it there will maintain the same directory structure as we have in our development directory, however.
    So, anyway, I see in the File class you have methods for getting absolute filepaths and directory names and such, but nothing for getting a relative link to another file.
    Does anyone know if such a class/method exists anywhere in std Java? Or how else I could go about doing this?
    Many thanks if you can help.

    Given a File object f then one can build the path to the root as a list of file names from f.getName() and iterating using f = f.getParentFile().
    Once you have the path lists for your two files then it is simple enough to find the branch point by moving forward through the lists until values differ. Building the relative path is then a matter of moving back through one using "../" until the branch point and then forward through the other until you reach the last element.

  • Relaive file paths in Java

    Hi,
    I have a file in c:\dev\core\CSF\csf\data\test.txt.
    My current directory is c:\dev\core\CSF\csf\build
    From my current working directory howdo i access test.txt using relative path.
    My code from is as follows
    Object.setKeystore("file://../data/test.txt"); NOte that i need a URL because the setKeystore() requires sURL as its input.The above code does not seem to change the directory from c:\dev\core\CSF\csf\build to c:\dev\core\CSF\csf\data\test.txt

      // Get the parent of a relative filename path
        File file = new File("Ex1.java");
        String parentPath = file.getParent();      // null
        File parentDir = file.getParentFile();     // null
        // Get the parents of an absolute filename path
        file = new File("D:\\almanac\\Ex1.java");
        parentPath = file.getParent();             // D:\almanac
        parentDir = file.getParentFile();          // D:\almanac
        parentPath = parentDir.getParent();        // D:\
        parentDir = parentDir.getParentFile();     // D:\
        parentPath = parentDir.getParent();        // null
        parentDir = parentDir.getParentFile();     // null
        //Don't have to use setKeystore... can just convert it it as follows....
        File file = new File("filename");
        // Convert the file object to a URL
        URL url = null;
        try {
            // The file need not exist. It is made into an absolute path
            // by prefixing the current working directory
            url = file.toURL();          // file:/d:/almanac1.4/java.io/filename
        } catch (MalformedURLException e) {
        // Convert the URL to a file object
        file = new File(url.getFile());  // d:/almanac1.4/java.io/filename
        // Read the file contents using the URL
        try {
            // Open an input stream
            InputStream is = url.openStream();
            // Read from is
            is.close();
        } catch (IOException e) {
            // Could not open the file
        }I hope this helps.

  • Relationship of codebase and code (relative path)..

    in tomcat installed directory, under ROOT directory, i have jsp folder and web-inf folder. all my jsp in /jsp/*.jsp and all my classes in /web-inf/classes/myservlets/*.class.
    I am trying to include applets for java plug-in and
    code like this
    <jsp:plugin type="applet'
    codebase="jsp"
    code="..\web-inf\classes\myservlets\MyTestApplets.class"
    width="475"
    height="350">
    this didn't work.
    Any idea about relative path about codebase and code? By the way, I am working on 2000
    Thanks.

    you can try to use absolute path begins with "http" in the codebase

Maybe you are looking for

  • ORA-00911: invalid character using multiple select statements

    I am getting an ORA-00911: invalid character error when trying to execute 2 select statements using ODP.NET. cmd.CommandText = "select sysdate from dual;select sysdate from dual;"; cmd.Connection = conn; cmd.CommandType = System.Data.CommandType.Text

  • Import QTVR into Flash

    Hi all, Wasn't sure which thread to put this in, apologies if its in the wrong one. Anyway, I was just wondering if it possible to import QTVR movies into Flash like you can with regular Quicktime movies, what QTVR has is controls that allow the user

  • I don't want Photo Stream to put all my iPhoto imports back to my iPhone!!

    When I import photos from the iPhone to iPhoto, the new Photo Stream function puts them right back to my iPhone!! Help!!!!

  • I book G4 (my daughters) won't start up

    If I put in disk warrior which I have, will that start up the G4 I book? Or is there a better way to try to get it going? Thanks, Dr. Steve

  • Illustrator CS6 crashes...

    Illustrator CS6 is consistently crashing when I zoom in or out and when I pan. By consistently, I mean that zooming and panning are the only actions that cause it to crash. It does not crash every time I zoom or pan. I believe it is graphics card and