I have tried the following code but java still says it cannot find the values. It only works if I set them in JVM before I even run my code. I just want to load them using a properties file. In my case file is being loaded put java properties is not being populated.
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.
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.
Alternatively, you can use Java 7's "try-with-resources" idiom, as InputStream
is AutoCloseable
.
Example (Java 7 style)
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:
my.key=foo
...
This will print:
foo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.