如何在Java中指定带有变量的文件路径?

huangapple go评论80阅读模式
英文:

How to specify the file path in java which has variable in it's path?

问题

我有两个项目。一个位于位置a,另一个位于位置b。

项目a需要从项目b的目录加载conf文件。
我不能硬编码文件的路径,因为位于b目录中的文件,如果我在不同的机器上运行,每台机器的用户名都可能不同,路径也可能不同。

因此,我想要的是,每个人都将他们的conf文件路径设置为.bashrc中的环境变量。这样,我希望在我的Java代码中使用导出的变量路径。现在的问题是,我该如何做到这一点?


以下是类似于我想要做的事情:

我在系统的.bashrc中有一个变量存储,如下所示:

export variableName1=~/path_to_file

现在我想在Java中使用这个变量来加载配置文件,如下所示:

Config config = ConfigFactory.parseFile(new File("${variableName1}/path_to_file"));

我该如何做到这一点呢?

我尝试通过以下方式获取variableName1的值:

String value = System.getProperty("variableName1");

或者

String value = System.getenv("variableName1");

但是这只会返回空值。

英文:

I have two projects. One at location a and other at b.

Project a needs to load the conf file from project b's directory.
I can't hardcode the path for file which is located in b's directory because If I run this on different machine everymachine's username will be different and path can be different as well.

So I want to do is, everyone sets their conf file path as environment varibale in .bashrc. That way I want to use exported variable path in my java code. Now the question is how do I do that?


Following is something similar to what I want to do:

I have one varibale stored in my system at .bashrc as follows:

export variableName1=~/path_to_file

Now I want to use this variable in java while loading the config file as follows:

        Config config = ConfigFactory.parseFile(new File("${variableName1}/path_to_file"));

How do I do that?

I tried getting the value of variableName1 as follows:

        String value =  System.getProperty("variableName1");
                          OR
        String value =  System.getenv("variableName1");

But this returns null value only.

答案1

得分: 0

这是一个环境变量,因此可通过以下方式访问:

String myDirectory = System.getenv("variableName1");
英文:

That's an environment variable so is accessed with

String myDirectory = System.getenv("variableName1");

答案2

得分: 0

Step 1:
你需要在.bashrc文件中使用export命令导出变量名,以便从所有终端访问。

export variableName1="~/path_to_file"

然后重新启动电脑。

Step 2:

在Java代码中,你可以通过以下方式获取该值:

String value = System.getenv("variableName1");
英文:

Step 1:
You need to export the variable name in .bashrc file for accessing from all terminal.

export variableName1="~/path_to_file"

Then restart the computer.

Step 2:

In Java code you can get the value by:

 String value =  System.getenv("variableName1");

huangapple
  • 本文由 发表于 2020年8月24日 16:28:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63557324.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定