In previous posts under DotEnv, whenever we called static “load” method on “DotEnv” class it used to load system environment values in addition to environment
values present in .env or .env file with custom name.
What if we want only the environment values present in the file and not the system environment values.
There is way to achieve this and I will show that in this post.
For our example we have .env file with below entries
MY_ENV_VAR1=some_value1
MY_ENV_VAR2=some_value2
Below is the complete main code for your reference
Main Class
1 package defaultPackage;
2
3 import io.github.cdimascio.dotenv.Dotenv;
4 import io.github.cdimascio.dotenv.DotenvEntry;
5
6 public class Example7 {
7 public static void main(String[] args) {
8 Dotenv dotenv = Dotenv.load();
9 for(DotenvEntry entry : dotenv.entries(Dotenv.Filter.DECLARED_IN_ENV_FILE)) {
10 System.out.println(entry.getKey() + ":" + entry.getValue());
11 }
12 }
13 }
In the above code at line 8 we are calling static “load” method on “Dotenv” class.
This will give us all environment values in the .env file including system environment values.
In the loop we are calling “entries” method and passing the enum “Dotenv.Filter.DECLARED_IN_ENV_FILE” as a parameter.
As a result of which we get environment values present only in files and not the system environment values.
In this way, we can get environment values present only in files.
Below is the output for your reference
Output
MY_ENV_VAR2:some_value2
MY_ENV_VAR1:some_value1