Logo

Programming-Idioms

  • Java
  • Lua

Idiom #106 Get program working directory

Assign to string dir the path of the working directory.
(This is not necessarily the folder containing the executable itself)

dir = os.getenv("PWD") or io.popen("cd"):read()

Tries to get a system environment variable PWD. If it is a linux system, it will contain working directory. Will ignore io.popen() then due to short-circuit evaluation.
If enviroment variable PWD doesn't exists, it executes cmd command "cd" and reads the result, which will work on windows systems.
String path = this.getClass().getClassLoader().getResource("").getPath();
import java.io.File;
String dir = new File("").getAbsolutePath();

"... If this abstract pathname is the empty abstract pathname then the pathname string of the current user directory, which is named by the system property user.dir, is returned."
String dir = System.getProperty("user.dir");

The "user.dir" property will return the user working directory.
with Ada.Directories; use Ada.Directories;
Dir : String := Current_Directory;

New implementation...
< >
programming-idioms.org