简体   繁体   English

找到java应用程序的相对路径

[英]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. 我已经在StackOverflow中阅读了与此相关的所有其他问题,但我没有找到任何明确的答案。 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("./")将返回指向您的java应用程序已启动目录的文件对象

new File("./myDirectory") will return a file object pointed at the myDirectory folder located in the directory your java application has been launched from new File("./myDirectory")将返回一个文件对象,该文件对象位于您的java应用程序已从其启动的目录中的myDirectory文件夹中

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: 这是您的属性文件(比如说config.properties)内容应该是这样的:

filesDirPath=\\usr\\home\\test filesDirPath =的\\ usr \\家\\测试

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

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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