我的任务是编写一些代码,根据我所处的环境(生产或测试)提取属性文件。所以 jar 文件在每个环境中都是相同的,但是一些变量会根据 jar 执行的环境而改变。导演看起来像这样:
[ProgramOne.jar ProgramTwo.jar ProgramThree.jar mypropertiesfile.properties]
我需要这些 jar 中的每一个来读取属性文件。我正在阅读这样的内容:
try(InputStream theResourceStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("mypropertiesfile.properties"))
我还没有访问这些环境的权限,并且将有一个非常小的窗口来实现此代码。我的问题是,根据我的情况,这是读取属性文件的正确方法吗?这会起作用吗?我试过在我的本地机器上加载文件,但一切都返回 null。
最佳答案
如果它不能在您的机器上运行,那么它可能无法在其他机器上运行。
当我认为您想从同一目录中的外部文件加载属性时,您似乎正在尝试从 Jar 加载资源。
试试这个:
与 test.properties
在与 Jar 相同的目录中,具有属性 my-property=this is a test
public class Main {
public static void main(String[] args){ new Main().test(); }
/** Usually gets the `JAR` directory or the `bin` when running in IDE */
public String getCodeSourcePath() throws SecurityException, URISyntaxException {
return getClass().getProtectionDomain().getCodeSource().getLocation()
.toURI().getPath();
}
public void test() {
// TODO handle exceptions, unlikely to occur unless you do something weird
String jarPath = getCodeSourcePath();
Properties properties = new Properties();
File file = new File(jarPath, "test.properties");
try (FileInputStream fis = new FileInputStream(file);) {
properties.load(fis);
}
System.out.println(properties.getProperty("my-property"));
}
}
输出:这是一个测试
关于java - 读取外部属性文件 Java/Linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51272703/