Accessing an environment variable

In this post under DotEnv, I will show with example how to access a particular environment variable.

For example I have created “.env” file with below data.

Env File

MY_ENV_VAR1=some_value1
MY_ENV_VAR2=some_value2

Now to retrieve the value of environment variable “MY_ENV_VAR1” we call the non static “get” method of “DotEnv” class as shown below

Main class

1  package defaultPackage;
2  
3  import io.github.cdimascio.dotenv.Dotenv;
4  
5  public class Example2 {
6      public static void main(String[] args) {
7          Dotenv dotenv = Dotenv.load();
8          System.out.println(dotenv.get("MY_ENV_VAR1"));
9      }
10 }

In the above code, at line 7 we load the “.env” file present in our project directory.

At line 8, we use “get” method of “DotEnv” class instance passing the environment variable name as a parameter.

In this way we can retrieve the value of a particular environment variable.

Leave a Reply