Loading .env file from a specific folder

In previous post under DotEnv, I showed that by default DotEnv checks for “.env” file in the project directory when static “load” method is called.

So if your project directory is in “D:\ProgrammingConcepts\JavaSEConcepts\DotEnvConcepts” the “.env” file should be present directly under the “DotEnvConcepts” folder.

If present in subfolders under “DotEnvConcepts” it will not load that file.

In this post I will show how to configure “DotEnv” to look for “.env” file in different folder.

As I said earlier by default DotEnv checks for “.env” file under current project directory.

To change default settings we need to configure “DotEnv” while creating an instance of it, which can be done using the below code snippet

    Dotenv.configure().directory("custom-folder").load();

In the above code snippet, we are changing the default behavior of “DotEnv” by calling static “configure” method and then setting the directory under which it has to find “.env” file by calling
“directory” method and at last we call “load” method to load the “.env” present at the specified directory.

In this way we can configure DotEnv to check for “.env” file in a specific folder other than project directory.

For our example I have placed a .env file in the path “D:\ProgrammingConcepts\JavaSEConcepts\DotEnvConcepts\custom-folder”.

Below is the complete 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 Example3 {
7      public static void main(String[] args) {
8          Dotenv dotenv = Dotenv.configure().directory("custom-folder").load();
9          for(DotenvEntry entry : dotenv.entries()) {
10             System.out.println(entry.getKey() + ":" + entry.getValue());
11         }
12         System.out.println("---------------------------------------");
13         dotenv = Dotenv.configure().directory("D:\\ProgrammingConcepts\\JavaSEConcepts\\DotEnvConcepts\\custom-folder").load();
14         for(DotenvEntry entry : dotenv.entries()) {
15             System.out.println(entry.getKey() + ":" + entry.getValue());
16         }
17     }
18 }

In the above main class we are showing how to use “directory” method using relative and absolute path.

Leave a Reply