In all my previous post under DotEnv, I showed how to load environment properties from a file named “.env”.
The “.env” file can be present in the project directory or in some other directory.
By default, DotEnv is configured to search under project directory.
In one of my previous posts, I showed how to change that default setting. Showed how to specify path to some other directory other than project directory containing the “.env” file.
Similarly by default DotEnv library is configured to search only for a file named “.env”.
We can change this default setting as shown in the below example.
For our example I have created a file named “custom-file.env” and placed in my project directory.
The contents of the file is as shown below
CUSTOM_FILE_MY_ENV_VAR1=some_value1
CUSTOM_FILE_MY_ENV_VAR2=some_value2
Now lets go through the code that loads from this newly added file.
Main class
1 package defaultPackage;
2
3 import io.github.cdimascio.dotenv.Dotenv;
4 import io.github.cdimascio.dotenv.DotenvEntry;
5
6 public class Example4 {
7 public static void main(String[] args) {
8 Dotenv dotenv = Dotenv.configure().filename("custom-file.env").load();
9 for(DotenvEntry entry : dotenv.entries()) {
10 System.out.println(entry.getKey() + ":" + entry.getValue());
11 }
12 }
13 }
In the above main code, at line 8. I am creating a “DotEnv” instance configured to read environment properties from “custom-file.env” file.
In the above code snippet, at line 8 we are changing the default behavior of “DotEnv” by calling static “configure” method and then setting the new file name by calling “filename” method.
In this way, we can change the default setting of DotEnv to read from file named other than “.env”.