[英]How do I set java jvm properties from run time
I have tried the following code but java still says it cannot find the values. 我尝试了以下代码,但是java仍然说它找不到值。 It only works if I set them in JVM before I even run my code. 仅当我在运行代码之前在JVM中设置它们时,它才有效。 I just want to load them using a properties file. 我只想使用属性文件加载它们。 In my case file is being loaded put java properties is not being populated. 在我的情况下,正在加载文件,而未填充Java属性。
Properties prop = new Properties();
InputStream in = MyClass.class.getResourceAsStream("/vars.options");
prop.load(in);
in.close();
System.setProperties(prop);
Your code doesn't set the properties object to the system properties. 您的代码未将properties对象设置为系统属性。
You are missing: 您不见了:
System.setProperties(prop);
Note 注意
Make sure to use a try
/ catch
/ finally
statement and to close your stream in the finally
block. 确保使用try
/ catch
/ finally
语句,并在finally
块中关闭流。
Alternatively, you can use Java 7's "try-with-resources" idiom, as InputStream
is AutoCloseable
. 另外,您可以使用Java 7的“ try-with-resources”习惯用法,因为InputStream
是AutoCloseable
。
Example (Java 7 style) 示例(Java 7样式)
try (InputStream in = Main.class.getResourceAsStream("/vars.options")){
Properties prop = new Properties();
prop.load(in);
System.setProperties(prop);
}
catch (IOException ioe) {
// TODO handle
}
System.out.println(System.getProperty("my.key"));
If in your src
root folder, the vars.options
file contains: 如果在src
根文件夹中,则vars.options
文件包含:
my.key=foo
... ...
This will print: 这将打印:
foo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.