简体   繁体   中英

Find relative path of java application

I have read all the other questions related to this in StackOverflow and I did not find any clear response. To cut it short, I have an application that will store some files in a directory that I will use than to process them. I have intentions of moving my app in different places (other computers) so I need to have a relative path to work with so that I will not change that in each time. Does anyone know how to get the relative path of the application (not the full path) so that I could use in this case? If what I am asking is not wright please tell me another way to achieve what I need. Thank you

Just use "./" .

No matter what directory your application has been launched from, "./" will always return that directory.

For example:

new File("./") will return a file object pointed at the directory your java application has been launched from

new File("./myDirectory") will return a file object pointed at the myDirectory folder located in the directory your java application has been launched from

Here is one approach:

I believe you need to define the path of directory containing the files in a configuration/property file. You can change the path in the configuration file when you move your application or the directory containing the file. This is how your properties file(let's say config.properties) contents should be:

filesDirPath=\\usr\\home\\test

And this what you should do in the code:

  private void readConfig()
    {
        Properties prop = new Properties();

        try {
               //load a properties file
            prop.load(new FileInputStream("config.properties"));

               //get the directory path property value
                String flesDirPath = prop.getProperty("filesDirPath");

                System.out.println("Files to be read are located in dir : "  + flesDirPath );


        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM