简体   繁体   English

java - 如何在路径中有变量的java中指定文件路径?

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

I have two projects.我有两个项目。 One at location a and other at b.一个在位置 a,另一个在 b。

Project a needs to load the conf file from project b's directory.项目a需要从项目b的目录中加载conf文件。 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.我不能硬编码位于 b 目录中的文件的路径,因为如果我在不同的机器上运行它,每台机器的用户名都会不同,路径也可能不同。

So I want to do is, everyone sets their conf file path as environment varibale in .bashrc.所以我想做的是,每个人都将他们的 conf 文件路径设置为 .bashrc 中的环境变量。 That way I want to use exported variable path in my java code.这样我想在我的java代码中使用导出的变量路径。 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:我在系统中的 .bashrc 中存储了一个变量,如下所示:

export variableName1=~/path_to_file

Now I want to use this variable in java while loading the config file as follows:现在我想在加载配置文件时在java中使用这个变量,如下所示:

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

How do I do that?我怎么做?

I tried getting the value of variableName1 as follows:我尝试按如下方式获取 variableName1 的值:

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

But this returns null value only.但这仅返回空值。

这是一个环境变量,因此可以使用

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

Step 1: You need to export the variable name in .bashrc file for accessing from all terminal.步骤1:您需要在.bashrc文件中export变量名称,以便从所有终端访问。

export variableName1="~/path_to_file"

Then restart the computer.然后重新启动计算机。

Step 2:第2步:

In Java code you can get the value by:在 Java 代码中,您可以通过以下方式获取值:

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

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

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