Loading .env files

In this post under DotEnv, I will show with example how to load a .env file.

Below is the complete main class

Main class

1  package defaultPackage;
2  
3  import io.github.cdimascio.dotenv.Dotenv;
4  import io.github.cdimascio.dotenv.DotenvEntry;
5  
6  public class Example1 {
7      public static void main(String[] args) {
8          Dotenv dotenv = Dotenv.load();
9          for(DotenvEntry entry : dotenv.entries()) {
10             System.out.println(entry.getKey() + ":" + entry.getValue());
11         }
12     }
13 }

In the above code, at line 8, we call static method “load” of “DotEnv” class.

This load method does the following
1) By default it searches for “.env” file in the project folder and if present loads the file
2) It also collects all the system environment variables.
3) and at the last returns an instance “DotEnv” class

For my example I have added an “.env” file with below data

env file

MY_ENV_VAR1=some_value1
MY_ENV_VAR2=some_value2

And then in the for loop we print the environment variables with their values.

In this way we can load .env files.

Leave a Reply